How to make a Generic Type Cast function

Riz picture Riz · Jul 30, 2011 · Viewed 121.9k times · Source

Possible Duplicate:
is there a generic Parse() function that will convert a string to any type using parse?

I want to make a generic function for doing some operations, like:

ConvertValue<T>(string value)

If T is int then the function will convert the value to int and return the result.

Similarly, if T is boolean, the function will convert the value to boolean and return it.

How to write this?

Answer

BrokenGlass picture BrokenGlass · Jul 30, 2011

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.