C#: Dynamic parse from System.Type
This should work for all primitive types, and for types that implement IConvertible
public static T ConvertTo<T>(object value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
EDIT : actually in your case, you can't use generics (not easily at least). Instead you could do that :
object value = Convert.ChangeType(myString, propType);
TypeDescriptor
to the rescue!:
var converter = TypeDescriptor.GetConverter(propType);
var result = converter.ConvertFrom(myString);
All primitive types (plus Nullable<TPrimitive>
, and numerous other built-in types) are integrated into the TypeConverter infrastructure already, and are thus supported 'out-of-the-box'.
To integrate a custom type into the TypeConverter
infrastructure, implement your own TypeConverter
and use TypeConverterAttribute
to decorate the class to be converted, with your new TypeConverter