Monday, May 24, 2010

Predicate: c# - String to Generic Type conversion

Lately I was searching about how to convert a string to another type, which is specified as Generic.

The solution is very simple and already present in the framework:



public static T To(this string text)
{
return (T)Convert.ChangeType(text, typeof(T));
}
// sample usage
int val = "124".To();
double dbl = "124.5".To();