3

I'm developing an app for Windows Store app and I have code like this.

public enum Categories { Cat1, Cat2, Cat3 } 

Is there any option to convert string[] cats = {"categoty 1", "category 2", "category 3"} to Enum?

I've tried using EnumMember attribute:

[DataContract] public enum Categories { [EnumMember(Value = "category 1")] Cat1, [EnumMember(Value = "category 2")] Cat2, [EnumMember(Value = "category 3")] Cat3 } 

...but still no luck with var cat = Enum.Parse(typeof(Categories), cats[0]);:

Exception thrown: 'System.ArgumentException' in mscorlib.ni.dll Requested value 'category 1' was not found. 

Any ideas?

2
  • 1
    With the attribute approach, you'd need to use reflection to get the attributes of all the enum values and compare it to your string. An easier way (although arguably slightly less easy to maintain) is to just include a Dictionary<string,Categories> that maps the string to the enum value. Commented Aug 30, 2016 at 20:05
  • 1
    the answer to this question might shed some light for you stackoverflow.com/questions/19767863/… Commented Aug 30, 2016 at 20:07

1 Answer 1

2
private static T GetValueFromEnumMember<T>(string value) { var type = typeof(T); if (type.GetTypeInfo().IsEnum) { foreach (var name in Enum.GetNames(type)) { var attr = type.GetRuntimeField(name).GetCustomAttribute<EnumMemberAttribute>(true); if (attr != null && attr.Value == value) return (T)Enum.Parse(type, name); } return default(T); } throw new InvalidOperationException("Not Enum"); } 

Usage:

var cat = GetValueFromEnumMember<Categories>(cats[0]); 
Sign up to request clarification or add additional context in comments.

1 Comment

Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.