Get Enum from Description attribute [duplicate]

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));

6 Answers
6

Leave a Comment