Conditional Attributes

1 07 2011

Conditional compilation can be a real pain. There are lots of situation where we want a DEBUG build to perform some operations that are not necessary in RELEASE. A good example is a method that checks an object’s pre- and post-conditions and print out some debug information.

private void CheckConditions()
{
#if DEBUG
    //check state, print out debug information etc.
#endif
}

So in DEBUG mode this method is compiled to include your checking code, in RELEASE this method is empty. That’s fine except you still pay the price of a method call whenever CheckConditions() is called elsewhere.

A better option is offered by the Conditional attribute. You apply the Conditional attribute to a method and the compiler detects that this method should be called only when in DEBUG mode. The difference is that the calls to CheckConditions() are removed from the RELEASE build while the body of the method remains the same. No empty methods being called!.

[Conditional("DEBUG")]
private void CheckConditions()
{
    //check state, print out debug information etc.
}

The difference here is that using #if #endif you ask the preprocesor to remove the source code between those directives whereas with the Conditional attribute you ask the compiler to remove calls to that method from the IL it produces.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: