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?

Vlad
  • 852
  • 10
  • 23
  • 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` that maps the string to the enum value. – Matt Burland Aug 30 '16 at 20:05
  • 1
    the answer to this question might shed some light for you http://stackoverflow.com/questions/19767863/cant-get-enum-to-convert-to-json-properly-using-json-net – Sam.C Aug 30 '16 at 20:07

1 Answers1

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]);
Vlad
  • 852
  • 10
  • 23
  • Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See [answer] for more information. – Heretic Monkey Aug 30 '16 at 21:22