views:

83

answers:

1

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

+5  A: 

System.Convert.ChangeType

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
cool , but the strange thing its named ChangeType , so i would thought that this function does some kind of cast and not parse
Karim
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