.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:


public class CategoryAttribute : Attribute

Declaring your decorated enum:

enum MyEnum





    [Category("This is bar")]





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);




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

    if (categories.Length == 0)


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




        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 *