SharpDeveloper
Smarter Debug Code With Conditional Compilation
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.
Related Reading:
Other Interesting Posts
-
Articles
- January 2011
- April 2010
- March 2010
- February 2010
- January 2010
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
-
Meta







