tags:

views:

36

answers:

3

I have an enum below which I need to be able to reference by passing in "Insured Only". When I do this it says that it cannot be found as the actual enum shows as InsuredOnly. Is there anyway I can pass in the correct value i.e. "Insured Only" instead of InsuredOnly?

 public enum EnumNames  
        {
            Administrator,
            [Description("Insured Only")]
            InsuredOnly, 
        }
+2  A: 

"Insured Only" is a string, where InsuredOnly is an enum. Even if you do a .ToString(), it will be "InsuredOnly"

There are several options here, to name a few:
1) Use a Dictionary<myenum,string> to map the values
2) Use a [Description("my description")] (see this article)
3) Use some kind of token in the enum, say an underscore, and use string.Replace()

Muad'Dib
+1  A: 

You can do this through reflection (did not do any extensive testing on the code, but hopefully you get the idea):

private static T GetEnumValue<T>(string description)
{
    // get all public static fields from the enum type
    FieldInfo[] ms = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static);
    foreach (FieldInfo field in ms)
    {
        // pull out the DescriptionAttribute (if any) from the field
        var descriptionAttribute = field
            .GetCustomAttributes(typeof(DescriptionAttribute), true)
            .FirstOrDefault();
        // Check if there was a DescriptionAttribute, and if the 
        // description matches
        if (descriptionAttribute != null
            && (descriptionAttribute as DescriptionAttribute).Description
                    .Equals(description, StringComparison.OrdinalIgnoreCase))
        {
            // return the field value
            return (T)field.GetValue(null);
        }
    }
    return default(T);
}
Fredrik Mörk
+1  A: 

Here's a handy generic method that should do what you want:

public T Parse<T>(string description) {
    foreach (FieldInfo field in typeof(T).GetFields()) {
        object[] attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if ((attributes.Length > 0)
            && ((DescriptionAttribute)attributes[0]).Description.Equals(description)
        ) return (T)field.GetRawConstantValue();
    }

    // use default parsing logic if no match is found
    return (T)Enum.Parse(typeof(T), description);
}

Usage example:

EnumNames value = Parse<EnumNames>("Insured Only");
Bradley Smith