Type converters let you convert one type to another type. Each type that you declare can optionally have a TypeConverter associated with it using the TypeConverterAttribute. If you do not specify one the class will inherit a TypeConverter from its base class.
The following methods deal with the type conversion work that is performed by TypeConverters.
// for conversion from another type to the type that this type converter is associated with public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType); public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value); // for conversion of this type to some other type public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType); public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType);
The above functions provide the core of TypeConverters. One reason for the confusion surrounding TypeConverters is the fact that they have other functions that are unrelated to the primary type conversion function. Methods such as public PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value) do not perform type conversion. They are present for another purpose.
Typically when we require access to the properties, events and methods we use a TypeDescriptor. However there are .NET framework elements such as the PropertyGrid that first access the TypeConverter and then query it for a list of Properties (it returns true when public bool GetPropertiesSupported(); is called). If the TypeConverter returns false from public bool GetPropertiesSupported(), then the TypeDescriptor is queried for such information. Deriving a type converter is an easy way to present properties, events etc in any manner that you want especially with the property grid. In your own code also when you access Property information it is good practice to query the TypeConverter first. So, presentation of object properties, methods and events is also a function of the TypeConverter. Unfortunately, the name ’TypeConverter’ does not hint at this function.
Enclosed is a small sample that illustrates the use of a custom Type Converter for conversion. Download TypeConverter.zip. Try the sample and it will be clear what Type Converters primarily do.
For more information on TypeDescriptors please refer to https://www.syncfusion.com/content/en-us/faq/windowsforms/search/705.aspx