Smarter Debug Code With Conditional Compilation
July 18th, 2007 by Sameer | Filed under .NET articles.Debug statements. We’ve all used debug statements at one time or another–most commonly to print out some values and see what they are. Commonly criticized (and rightly so) as a "beginners" way to debug, many developers usually advance to a proper debugger and leave behind semi-useless print statements.
But wait.
Are they useless?
The idea of print statements is to show something to the developer–print some value.
But what about more advanced debug code? Extra buttons that let you skip and automate tedious steps. Labels that show you that certain values are meeting their expectations. Forms that run in the background and churn out useful information.
"Ok, sure," you might say, "but, eh, I have to remove that for the release version."
But do you?
.NET says you don’t have to.
How does it work?
.NET has something called conditional compilation–the gist of it is that, like System.Diagnostics.Assert, certain methods are only compiled into the code when you’re running in debug mode. Otherwise, they’re ignored, and all calls to those methods do nothing. So you can happily introduce function calls all over the place to help you test your code, without worrying about the extra overhead of it compiling into production code (not to mention having to remove it from your application).
How do you do it? Simply add the following attribute to your desired methods:
[System.Diagnostics.Conditional("DEBUG")]
And VOILA! .NET leaves the code uncompiled in Release mode, and all function calls to that method are removed.
So go, and enjoy your newfound powers! And remember–it’s not about print statements. Smart debugging code can be a beneficial aid to development. It’s a tool for you to use, just like any other tool. Don’t misuse it.
