I'd like to have a simple helper method for converting a string to an Enum. Something like the following, but it doesn't like T as the first argument in the Enum.Parse. The error is T is a Type Parameter but is used like a variable.
public static T StringToEnum<T>(String value)
{
return (T) Enum.Parse(T,value,true) ;
}
Try this:
public static T StringToEnum<T>(String value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
public static T StringToEnum<T>(String value)
{
return (T) Enum.Parse(typeof(T),value,true) ;
}
What you were doing is like using 'int' as a Type, but it is not a Type object. To get the Type object, you would use typeof(int).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With