Sunday, December 30, 2007

Enums and Custom Attributes

A few projects ago, while working with Greg Martin, I discovered the benefit of using custom attributes with enums. It is a great way to empower your enums to replace custom logic in your applications. Since then, I have been on a bit of a attribute rampage, and I swear it has simplified many complex scenarios, and reduced the amount of custom code I would normally write.

Here are the bits, and please excuse my cheesy example, or just make fun of it.

I use an interface which my custom attributes derive from, in addition to deriving from System.Attribute. The interface merely enforces a property named Value to be defined. The interface is used in a later static method, as you will see.


I create a custom attribute deriving from System.Attribute and my interface.



I add my custom attribute to a targeted enum.



I use a static generic method to retrieve the custom attribute value for a given enum value.



I retrieve my attribute value in code with a simple "one-liner".



When I see another need for a custom attribute and I already have a solid pattern in place. Just add a new attribute class, modify my enum, and off I go.





In my applications, I continue to find more and more ways to use attributes and enums together. Hope you find this useful as well.

9 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. where do you put the static method

    ReplyDelete
  3. >where do you put the static method

    I think in:
    public static class EnumHelper

    ReplyDelete
  4. Thanbks Joel!! You have honestly saved me from hundreds of lines of patched code!!!!

    ReplyDelete
  5. Its really great piece of code to understand attributes.

    Thank you Joel

    ReplyDelete
  6. Great piece of code! thanks :)

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Good work - now we could create NoSQL database based on Enum and Custom attributes (just kidding :)).

    ReplyDelete