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 ...
Building off of the correct answer from Jon Skeet, you need to use the
TypeDescriptor
to do the conversion. Change your test code from:To:
and all should be well.