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.

Welcome to my Blog!

I find myself reading more and more blogs these days, and enjoying every minute of it. I justed started using Google Reader. Check it out if you haven't already. At any rate, inspired by reading great posts elsewhere, I figured it might be time to start blogging a bit myself.

This blog will probably be Developer-focused, but you may see a bit of humor/family/sports content here and there. Enjoy!