.NET: It is possible to apply attributes to enum members

For a long time I was sure it is not supported, because there was no corresponding AttributeTargets value.

It turns out, that you can do it by using AttributeTargets.Field. Declaring your attribute class:

[AttributeUsage(AttributeTargets.Field)]

public class CategoryAttribute : Attribute

Declaring your decorated enum:

enum MyEnum

{

    [Category("foo")]

    Foo,

 

    [Category("This is bar")]

    Bar,

 

    Baz

}

Reading attribute values:

foreach (MyEnum x in Enum.GetValues(typeof(MyEnum)))

{

    MemberInfo[] info = typeof(MyEnum).GetMember(x.ToString());

    if (info.Length != 1)

    {

        Console.WriteLine("Get {0} members for {1}", info.Length, x);

        continue;

    }

 

    Attribute[] categories = Attribute.GetCustomAttributes(info[0], typeof(CategoryAttribute));

    if (categories.Length == 0)

    {

        Console.WriteLine("{0}: No category", x);

    }

    else

    {

        CategoryAttribute category = (CategoryAttribute)categories[0];

        Console.WriteLine("{0}: {1}", x, category.Category);

    }

}

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *