Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeConverter cannot convert from System.String

I'm trying to convert a string to its corresponding class (i.e. "true" to true). And I get "TypeConverter cannot convert from System.String". The value passed is "true".

Am I calling the method in the wrong way?

public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
    Type type = typeof(T);
    T ret = new T();

    foreach (var keyValue in source)
    {
        type.GetProperty(keyValue.Key).SetValue(ret, keyValue.Value.ToString().TestParse<T>(), null);
}

    return ret;
}

public static T TestParse<T>(this string value)
{
    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
like image 538
Lasse Edsvik Avatar asked Dec 22 '11 10:12

Lasse Edsvik


2 Answers

The problem is that the T you pass to the TestParse method is not the type bool but the type of the class you want to create. If you change the line to

public static bool TestParse(this string value)
    {
        return (bool)TypeDescriptor.GetConverter(typeof(bool)).ConvertFromString(value);
    }

It works for the bool case but obviously not for other cases. You need to get the type of the property you want to set via reflection and pass it to the TestParse method.

public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
    Type type = typeof(T);
    T ret = new T();

    foreach (var keyValue in source)
    {
        var propertyInfo = type.GetProperty(keyValue.Key);
        propertyInfo.SetValue(ret, keyValue.Value.ToString().TestParse(propertyInfo.PropertyType), null);
    }

    return ret;
}

public static object TestParse(this string value, Type type)
{
    return TypeDescriptor.GetConverter(type).ConvertFromString(value);
}

I would also change the TestParse method from an Extension Method to a normal method because it feels kinda weird

like image 129
kev Avatar answered Nov 10 '22 04:11

kev


Do it as it was done in this answer:

return (T)Convert.ChangeType(value, typeof(T));

where T is the target Type and value is of Type string
EDIT: this only works for IConvertible implementers...

like image 26
Adam Avatar answered Nov 10 '22 02:11

Adam