Most of the common types have a “TryParse” method available. Here’s a method you can use to dynamically call the corresponding TryParse method for a specific Type:
public static T ConvertValue<T>(string stringValue)
{
if (typeof(T) == typeof(string))
return (T)Convert.ChangeType(stringValue, typeof(T));
var type = typeof(T);
bool nullableType = type.IsGenericType
&& type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
if (nullableType)
{
if (stringValue == null)
return default(T);
type = new NullableConverter(type).UnderlyingType;
}
Type[] argTypes = { typeof(string), type.MakeByRefType() };
var tryParse = type.GetMethod("TryParse", argTypes);
if (tryParse == null)
{
string exceptionMessage = string.Format("A method named 'TryParse' does not exist for the '{0}' Type.", type.FullName);
throw new InvalidOperationException(exceptionMessage);
}
object[] args = { stringValue, null };
bool successfulParse = (bool)tryParse.Invoke(null, args);
if (!successfulParse)
throw new InvalidCastException();
return (T)args[1];
}
I’m currently using this in a code generation scenario where I have a string value and “T” is known at generation time. Enjoy.