Alex K Alex K - 15 days ago 4
C# Question

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")]
[Description("Name With Spaces2")]

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.


This should do what you need.

var type = typeof(FunkyAttributesEnum);
var memInfo = type.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
var description = ((DescriptionAttribute)attributes[0]).Description;