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));
Should be pretty straightforward, its just the reverse of your previous method;
Usage:
You can't extend
Enum
as it's a static class. You can only extend instances of a type. With this in mind, you're going to have to create a static method yourself to do this; the following should work when combined with your existing methodGetDescription
:And the usage of it would be something like this:
rather than extension methods, just try a couple of static methods
and use here
Usage:
You need to iterate through all the enum values in Animal and return the value that matches the description you need.
The solution works good except if you have a Web Service.
You would need to do the Following as the Description Attribute is not serializable.