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?
While probably not as clean looking as the IConvertible
approach, you could always use the straightforward checking typeof(T)
to return a T
:
public static T ReturnType<T>(string stringValue)
{
if (typeof(T) == typeof(int))
return (T)(object)1;
else if (typeof(T) == typeof(FooBar))
return (T)(object)new FooBar(stringValue);
else
return default(T);
}
public class FooBar
{
public FooBar(string something)
{}
}
ConvertValue( System.Object o ), then you can branch out by o.GetType() result and up-cast o to the types to work with the value.
Source: Stackoverflow.com