Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting attributes of Enum's value

I would like to know if it is possible to get attributes of the enum values and not of the enum itself? For example, suppose I have the following enum:

using System.ComponentModel; // for DescriptionAttribute  enum FunkyAttributesEnum {     [Description("Name With Spaces1")]     NameWithoutSpaces1,         [Description("Name With Spaces2")]     NameWithoutSpaces2 } 

What I want is given the enum type, produce 2-tuples of enum string value and its description.

Value was easy:

Array values = System.Enum.GetValues(typeof(FunkyAttributesEnum)); foreach (int value in values)     Tuple.Value = Enum.GetName(typeof(FunkyAttributesEnum), value); 

But how do I get description attribute's value, to populate Tuple.Desc? I can think of how to do it if the Attribute belongs to the enum itself, but I am at a loss as to how to get it from the value of the enum.

like image 693
Alex K Avatar asked Nov 25 '09 19:11

Alex K


People also ask

How do I find enum attributes?

Enum. GetValues(typeof(FunkyAttributesEnum)); foreach (int value in values) Tuple. Value = Enum. GetName(typeof(FunkyAttributesEnum), value);

What is description in enum in C#?

Definition. An Enumeration (or enum ) is a data type that includes a set of named values called elements or members. The enumerator names are usually identifiers that behave as constants in the language.

What is enum variable?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


1 Answers

This should do what you need.

try {   var enumType = typeof(FunkyAttributesEnum);   var memberInfos =    enumType.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());   var enumValueMemberInfo = memberInfos.FirstOrDefault(m =>    m.DeclaringType == enumType);   var valueAttributes =    enumValueMemberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);   var description = ((DescriptionAttribute)valueAttributes[0]).Description; } catch {     return FunkyAttributesEnum.NameWithoutSpaces1.ToString() }  
like image 186
Bryan Rowe Avatar answered Oct 22 '22 20:10

Bryan Rowe