Geeks With Blogs
Greg Young Greg.ToString()

Let me just say that so far this is #4 on the best features in 2.0 list.

If you remember in 1.x we had the Conditional Attribute that we could use in cases on a class or method. It would allow use to say ..

[Conditional(“Bar“]
public class Foo {
}

If “Bar“ was true, the class would be compiled into the resulting assembly. If not, the class and ALL USAGES of the class would not be compiled into the resulting assembly. This pattern was commonly used for things like debug logging. This was great except for one thing ... it didn't work with attributes.

I use lots of attributes in my code that are important for development of the application .. they are not required at runtime.

[CodeTestCoverageRequirement]

I later use this attribute in conjunction with a coverage tool to make SURE the code is actually coverred :) (can start sending emails and making lots of noise automatically if its not :)) I am sure we can all think of lots of places that we use such things in our code that we care about dearly, but are of no use to the redistributable portion of our code.

Since I do not wish to distribute these attributes in my production version I would often times end up with code that looked something like this since [Conditional] could not remove attribute based references to the class.

#if something
[CodeTestCoverageRequirement]
#endif

There were a few problems with this pattern. The largest is that it left it to me to remember to put the #if around the code, otherwise it would be renderred to the production version. The second problem is that those who know me know that I am a terrible typist and try to avoid it at all costs ... I had to type these ifs everywhere I placed the attribute, this would then lead me back to problem #1 because I am lazy :)

2.0 is smart enough to remove references made by attributes so I can now write the code as follows.

[Conditional(“InternalBuild“)]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CodeTestCoverageRequirement : Attribute {
}

Now if I use the attribute on a class such as ..

[CodeTestRequirement]
public class Foo {
}

The output of the attribute will vary depending whether or not I have the “InternalBuild” conditional set.

This removes problem #1 as the definition is finally moved to the attribute itself and it removes problem #2 as I no longer need to type the ifs :D

 

Posted on Sunday, April 30, 2006 11:20 PM Tips and Tricks | Back to top


Comments on this post: 2.0 Conditional Attributes

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Greg Young | Powered by: GeeksWithBlogs.net