Reputation: 1312
In the code below I am just coverting a string ("medium" for example) to its Enum value. What I need to be able to do is rather than having Opacity as a fixed Enum type, pass that in as an argument as well so that the function operates on any Enum. This seems to be proving more difficult than I anticipated, i.e. 'Enum MyEnum' doesn't work. Solutions anyone?
public enum Opacity
{
Low,
Medium,
High
}
public static Enum StringToEnum(String str)
{
return (Opacity)Enum.Parse(typeof(Opacity), str, true); // Case insensitive
}
Upvotes: 2
Views: 254
Reputation: 9356
public static T StringToEnum<T>(String str) where T : struct
{
return (T)Enum.Parse(typeof(T), str, true);
}
Upvotes: 9