C #, StringToEnum, can I make it a generic function from this

I would like to have a simple helper method for converting a string to Enum. Something like the following, but T doesn't like it as the first argument in Enum.Parse. Error T is a type parameter, but is used as a variable.

public static T StringToEnum<T>(String value) { return (T) Enum.Parse(T,value,true) ; } 
+4
source share
3 answers

Try the following:

 public static T StringToEnum<T>(String value) { return (T)Enum.Parse(typeof(T), value, true); } 
+7
source
 public static T StringToEnum<T>(String value) { return (T) Enum.Parse(typeof(T),value,true) ; } 

What you did is like using "int" as a type, but it is not a Type object. To get a Type object, you must use typeof (int).

+2
source

Here is the extension of the method that I am using.

 /// <summary> /// Will parse and string value and return the Enum given. Case is ignored when doing the parse. /// </summary> /// <param name="typeOfEnum">The type of the Enum to Parse</param> /// <param name="value">The string value for the result of the Enum</param> /// <param name="errorValue">If an error is encountered this value is returned. (For example could be an Enum)</param> /// <returns>Returns Enum Object</returns> public static T ToEnum<T>(this string value) { return (T)Enum.Parse(typeof(T), value, true); } 
0
source

All Articles