views:

502

answers:

2

Hi everyone,

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:

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.

Thank you.

+10  A: 

This should do what you need.

        var type = FunkyAttributesEnum.GetType();
        var memInfo = type.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());
        var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
        var description = ((DescriptionAttribute)attributes[0]).Description;
Bryan Rowe
FunkyAttributesEnum.ToString() should be FunkyAttributesEnum.NameWithoutSpaces1.ToString(), otherwise it worked flawlessly, and I adapted it to integrate seamlessly with the way I had values setup. Green checkmark is yours as soon as that little omission is fixed :) Thanks much!
Alex K
Sorry, I was in a rush to get my answer in first : )
Bryan Rowe
+1  A: 

Alternatively, you could do the following:

Dictionary<FunkyAttributesEnum, string> description = new Dictionary<FunkyAttributesEnum, string>()
    {
      { FunkyAttributesEnum.NameWithoutSpaces1, "Name With Spaces1" },
      { FunkyAttributesEnum.NameWithoutSpaces2, "Name With Spaces2" },
    };

And get the description with the following:

string s = description[FunkyAttributesEnum.NameWithoutSpaces1];

In my opinion this is a more efficient way of doing what you want to accomplish, as no reflection is needed..

Ian P
Sure, but reflection isn't nearly as bad as people make it out to be.
Bryan Rowe
Not saying it's bad -- I use it all the time. It is often used needlessly, though. :)
Ian P
This solution moves the description away from the enum itself, creating at least two big problems. First, if someone adds a new enum constant , they will need to know to go to this other place to add an entry there as well. Attributes are a clear sign to a maintainer of what they need to do. My second problem with it is that it's just a lot more code. Attributes are compact.
Scott Bilas