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);
}
The problem is that the
Tyou pass to theTestParsemethod is not the type bool but the type of the class you want to create. If you change the line toIt 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
TestParsemethod.I would also change the
TestParsemethod from an Extension Method to a normal method because it feels kinda weird