Lasse Edsvik Lasse Edsvik - 17 days ago 5
C# Question

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);
}

kev kev
Answer

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

Comments