A less-known yet very useful component in .NET is the TypeConverter class. It provides a standardised way to convert between data types — and the runtime uses it internally in many places (property grids, XML serialisation, ASP.NET model binding).
Basic Usage
TypeDescriptor.GetConverter returns the converter registered for any given type. Many primitive types and common framework types have converters registered by default inside ReflectTypeDescriptionProvider:
csharp
// Convert a string to an int using the registered TypeConverter
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
int value = (int)intConverter.ConvertFromString("42");
// Works with any type that has a registered converter
TypeConverter colorConverter = TypeDescriptor.GetConverter(typeof(Color));
Color red = (Color)colorConverter.ConvertFromString("Red");Custom TypeConverter
Implement TypeConverter and attach it to your class with [TypeConverter(typeof(...))]. Override CanConvertFrom / ConvertFrom for parsing and ConvertTo for formatting:
csharp
// Attach a custom converter via attribute
[TypeConverter(typeof(PointConverter))]
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
public class PointConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
=> sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string s)
{
var parts = s.Split(',');
return new Point { X = int.Parse(parts[0].Trim()), Y = int.Parse(parts[1].Trim()) };
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
=> destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is Point p)
return quot;{p.X},{p.Y}";
return base.ConvertTo(context, culture, value, destinationType);
}
}
// Usage: "10,20" → Point { X = 10, Y = 20 }
var converter = TypeDescriptor.GetConverter(typeof(Point));
var point = (Point)converter.ConvertFromString("10, 20");