I learned something pretty cool about .NET attributes today. While I have known about Obsolete() for some time, I just learned about Conditional(). Consider this code:

void ProductionMethod()
{
   WriteSomeImportantData();
   WriteDebugInfo();
}
[System.Diagnostics.Conditional("DEBUG")]
void WriteDebugInfo()
{
   // Display helpful debugging info
}

Traditionally, the call to WriteDebugInfo() would be enclosed within a preprocessing directive (#IF…#ELSE…#ENDIF) to eliminate the method call when the application is compiled in release mode. The Conditional() attribute replaces that rather ugly style with a single line of code as shown above. The compiler will automatically remove all calls to the decorated method unless the condition is true. This means you can make all the calls you want to WriteDebugInfo() without affecting code readability or production performance!

You may be thinking that this isn’t much of an improvement, in which case you’re wrong. By moving the decision into an attribute, you get all the existing attribute functionality supported by the framework. Want to know how many debug methods exist in your project? Would you prefer to manually search for and count all the instances, or write a few lines of code to reflect over the entire assembly? That’s just the beginning of it.

Advertisements