Sunday, October 25, 2009

The Conditional Attribute


The conditional attribute is a really cool why of compiling in or out an entire method in your code. The cool thing about it is the compiler automatically compiles in/out not only the method itself, but also all the calls to it.

The conditional attribute works with conditional compilation variables, which can be set in the Project Properties window on the Build tab. By default the Debug build defines a DEBUG variable, which is often useful.


Once you’ve got a variable defined for your purpose, you decorate your method with the conditional attribute and provide the variable name. Let’s say you have a LogDebugInfo method that you only want called in debug builds. Declare the method like this;

private void LogDebugInfo(string debugInfo)
  //Code here to log the value of debugInfo.

Now all you have to do is call the method as you normally would. When you compile or run your code as a debug build the LogDebugInfo method will be called normally, but when you build a release version the LogDebugInfo method and all calls to it will be stripped out of your code automatically.

You need to be careful though, that your methods that are marked with the Conditional attribute have no side-effects on the state of your application. That is, they should not change class level fields or static values, or create or dispose objects that the rest of your code depends on. If you’re not careful about that, you may end up with errors that occur in one build and not another because some part of your code is dependent of state that only occurs when the conditional method is compiled in.

Having said all that, and while I believe the Conditional Attribute is cool where you can use it, there are some subtle gotcha’s that Eric Lippert has explained on his blog.

No comments:

Post a comment