Reputation: 24067
I want a function that can convert "string" to a given type T. I.e. I want to implement such function:
T convertTo<T>(string stringToConvert)
T could be actually either simple type or enum, but i don't know how to check actual T type at runtime. I.e. I can't write something like that:
if (T instanceof MyEnum) { return MyEnum.Parse(stringToConvert); }
How can I implement my function then?
Upvotes: 0
Views: 743
Reputation: 24067
finally I've implemented function this way:
private static T ConvertFromString<T>(string text)
{
if (typeof(Enum).IsAssignableFrom(typeof(T)))
{
try
{
return (T)Enum.Parse(typeof(T), text);
}
catch (ArgumentException e)
{
return default(T);
}
}
return (T)Convert.ChangeType(text, typeof(T));
}
Upvotes: 0
Reputation: 1246
if (typeof(T) == typeof(MyEnum))
return (T)Enum.Parse(typeof(T), stringToConvert);
Upvotes: 1