Jerry Nixon @Work: Custom System.Attribute

Jerry Nixon on Windows

Friday, October 19, 2007

Custom System.Attribute

It took me a while to even understand why to use a custom attribute.

A custom attribute simply decorates something so it can be specially identified during reflection. Reflection is not always bad, you know, but were you considering a high-transaction situation for this, you are likely looking at the wrong solution for your problem.

I have created a simple console app sample:

[snip]

The output shows one of the biggest dangers of custom attributes. That is, the custom attribute class is instantiated at the instantiation of the decorated class as well as every time the decorated object is accessed and attribute is accessed.

The output of the sample class is as follows:

* MyAttributeOne('MyMethodOne()') just fired!
* MyAttributeOne('MyMethodTwo()') just fired!
* MyAttributeOne('MyMethodThree()') just fired!
MyMethod with MyAttributeOne: MyMethodOne
* MyAttributeOne('MyMethodOne()') just fired!
Value = MyMethodOne()
MyMethod with MyAttributeOne: MyMethodTwo
* MyAttributeOne('MyMethodTwo()') just fired!
Value = MyMethodTwo()
MyMethod with MyAttributeOne: MyMethodThree
* MyAttributeOne('MyMethodThree()') just fired!
Value = MyMethodThree()
* MyAttributeTwo() just fired!
* MyAttributeTwo() just fired!
MyMethod with MyAttributeTwo: MyMethodThree
MyMethod with MyAttributeTwo: MyMethodFour
Hit any key to continue...


The sheer quantity of "fired!" for attributes on methods in a class that is NEVER instantiated is terrifying. Now, don't hear that you should never use attributes or avoid injection completely. The real point is to be aware of how these things work.

So, why would you use custom attributes? I can't come up with a valid reason other than injection. And, to be honest, I can BARELY come up with a valid (real world) reason to use injection.