Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an enum value by its Description Attribute [duplicate]

Tags:

c#

reflection

This may seem a little upside down faced, but what I want to be able to do is get an enum value from an enum by its Description attribute.

So, if I have an enum declared as follows:

enum Testing {     [Description("David Gouge")]     Dave = 1,     [Description("Peter Gouge")]     Pete = 2,     [Description("Marie Gouge")]     Ree = 3 } 

I'd like to be able to get 2 back by supplying the string "Peter Gouge".

As a starting point, I can iterate through the enum fields and grab the field with the correct attribute:

string descriptionToMatch = "Peter Gouge"; FieldInfo[] fields = typeof(Testing).GetFields();  foreach (FieldInfo field in fields) {     if (field.GetCustomAttributes(typeof(DescriptionAttribute), false).Count() > 0)     {         if (((DescriptionAttribute)field.GetCustomAttributes(typeof(DescriptionAttribute), false)[0]).Description == descriptionToMatch)         {          }     } } 

But then I'm stuck as to what to do in that inner if. Also not sure if this is the way to go in the first place.

like image 731
DavidGouge Avatar asked Aug 06 '10 09:08

DavidGouge


People also ask

How do you find the underlying value of an enum?

To get the enum's underlying value, we can use the Convert. GetTypeCode() method.

What is enum description?

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy.

Do enum values have to be unique?

CA1069: Enums should not have duplicate values.

Can enum have attributes?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).


2 Answers

Using the extension method described here :

Testing t = Enum.GetValues(typeof(Testing))                 .Cast<Testing>()                 .FirstOrDefault(v => v.GetDescription() == descriptionToMatch); 

If no matching value is found, it will return (Testing)0 (you might want to define a None member in your enum for this value)

like image 61
Thomas Levesque Avatar answered Sep 29 '22 16:09

Thomas Levesque


return field.GetRawConstantValue(); 

You could of course cast it back to Testing if required.

like image 44
Ani Avatar answered Sep 29 '22 18:09

Ani