Question

If I create a class for customized displaying of an enumeration as follows:

public class MyEnumConverter : EnumConverter
{
    public MyEnumConverter(Type type) : base(type)
    {
    }
    public override object ConvertTo(...)
    public override object ConvertFrom(...)
}

When I tag an enum with MyEnumConverter as the TypeConverter:

[TypeConverter(typeof(MyEnumConverter))]
public enum MyEnum
{
    SomeValue,
    OtherValue
}

It works as expected. How does the EnumConverter constructor receive the required type parameter representing the enum type? Does TypeConverter know how to deal specifically with EnumConverter and fill this in for me? Is this syntactic sugar for something going on in the background? Is this behaviour customizable such that if I want to implement a parameterized constructor for a custom TypeConverter, that I can inform TypeConverter how to handle my custom constructor?

Was it helpful?

Solution

It looks like, internally, TypeConverter handles the procurement of the required converter using a complicated nested if statement. Something like (source):

    internal static TypeConverter GetCoreConverterFromCustomType(Type type)
    {
        TypeConverter typeConverter = null;
        if (type.IsEnum)
        {
            // Need to handle Enums types specially as they require a ctor that
            // takes the underlying type.
            typeConverter = new System.ComponentModel.EnumConverter(type);
        }
        else if (typeof(Int32).IsAssignableFrom(type))
        {
            typeConverter = new System.ComponentModel.Int32Converter();
        }
        else if (typeof(Int16).IsAssignableFrom(type))
        {
            typeConverter = new System.ComponentModel.Int16Converter();
        }
        //...

From the first if statement you can see that it knows to pass the special Type parameter into the constructor.

As an answer to the second question of can I create a custom TypeConverter with a custom-parameterized constructor that will play nicely with TypeConverter, it looks doubtful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top