Get Enum from Description attribute

fearofawhackplanet picture fearofawhackplanet · Dec 6, 2010 · Viewed 202.3k times · Source

Possible Duplicate:
Finding an enum value by its Description Attribute

I have a generic extension method which gets the Description attribute from an Enum:

enum Animal
{
    [Description("")]
    NotSet = 0,

    [Description("Giant Panda")]
    GiantPanda = 1,

    [Description("Lesser Spotted Anteater")]
    LesserSpottedAnteater = 2
}

public static string GetDescription(this Enum value)
{            
    FieldInfo field = value.GetType().GetField(value.ToString());

    DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
                as DescriptionAttribute;

    return attribute == null ? value.ToString() : attribute.Description;
}

so I can do...

string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"

now, I'm trying to work out the equivalent function in the other direction, something like...

Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));

Answer

max picture max · Dec 6, 2010
public static class EnumEx
{
    public static T GetValueFromDescription<T>(string description) where T : Enum
    {
        foreach(var field in typeof(T).GetFields())
        {
            if (Attribute.GetCustomAttribute(field,
            typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentException("Not found.", nameof(description));
        // Or return default(T);
    }
}

Usage:

var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");