I want to convert a string to a generic type like int
or date
or long
based on the generic return type.
Basically a function like Parse<T>(String)
that returns an item of type T
.
For example if a int was passed the function should do int.parse
internally.
As per your example, you could do:
int i = (int)Convert.ChangeType("123", typeof(int));
DateTime dt = (DateTime)Convert.ChangeType("2009/12/12", typeof(DateTime));
To satisfy your "generic return type" requirement, you could write your own extension method:
public static T ChangeType<T>(this object obj)
{
return (T)Convert.ChangeType(obj, typeof(T));
}
This will allow you to do:
int i = "123".ChangeType<int>();