well 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(String) that returns an item of type T.
for example if a int was passed the function should do int.parse internally
thanks
views:
83answers:
1
+5
A:
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>();
Ani
2010-08-17 12:48:15
cool , but the strange thing its named ChangeType , so i would thought that this function does some kind of cast and not parse
Karim
2010-08-17 12:51:42
MSDN says it is simply a wrapper that finds the right conversion method on the source object, requiring that it implements the IConvertible interface.
Ani
2010-08-17 12:58:17