Casting or Parsing a variable in generic type member variable in C#

Microsoft .Net already has a bunch of great string conversion routines you can use! A TypeConverter can do most of the heavy lifting for you. Then you don't have to worry providing your own parsing implementations for built-in types. Note that there are locale-aware versions of the APIs on TypeConverter that could be used if you need to handle parsing values expressed in different cultures. The following code will parse values using the default culture:


public object Convert(string member, string value)
{
    Type type = typeof(T).GetProperty(member).PropertyType;
    var converter = TypeDescriptor.GetConverter(type);
    return converter.ConvertFromString(value);
}
Previous
Next Post »