C# TypeConverter.ConvertFrom() problem

cnettype conversiontypeconverter

I have a problem with the following code which returns an object from a string:

[TypeConverter(typeof(MyConverter))]
public class MyClass
{
    public string s;
}

public class MyConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return (sourceType == typeof(string)) ? true : base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value is string)
        {
            MyClass m = new MyClass();
            m.s = (string)value;
            return m;
        }

        return base.ConvertFrom(context, culture, value);
    }
}

When I try to use with this code:

string s_test = "test";

MyClass m_test;

m_test = (MyClass)Convert.ChangeType(s_test, typeof(MyClass));

I get the error message

Invalid cast from 'System.String' to
'MyClass'.

What is wrong in my code?
Note that I must use the ConvertFrom() method…

Thank you in advance for your help.

Stack trace:

[InvalidCastException: Invalid cast from 'System.String' to 'MyClass'.]
   System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) +9496632
   System.String.System.IConvertible.ToType(Type type, IFormatProvider provider) +8
   System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) +9531720
   System.Convert.ChangeType(Object value, Type conversionType) +32
   OrderController.Index() in [...].cs:70
   ... omitted for brevity ...

Best Answer

You're expecting Convert.ChangeType to use a TypeConverter if one is present - it doesn't. TypeConverter is usually used in conjunction with TypeDescriptor (often implicitly in UI frameworks).

Related Topic