Something like this?
public static T ConvertValue<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
You can then use it like this:
int val = ConvertValue<int>("42");
Edit:
You can even do this more generic and not rely on a string
parameter provided the type U
implements IConvertible
- this means you have to specify two type parameters though:
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
I considered catching the InvalidCastException
exception that might be raised by Convert.ChangeType()
- but what would you return in this case? default(T)
? It seems more appropriate having the caller deal with the exception.