Conditional debug statements in Visual Studio
It has taken a me a long time to finally get this neat Visual Studio trick working. Despite it being a very powerful addition to the development and debugging process, there doesn’t seem to be much information about it, apart from the small entry on MSDN discussing the preprocessor.
To perform different actions or execute different blocks of code depending on your build configuration (think debug or release), you will need to define a new symbol for your build configuration. In my scenario, I was interested in executing a block of code whilst in debug mode, but not perform it in release.
- In Visual Studio select the Project menu and click “(Project) Properties” at the bottom of the menu.
- Select the Build tab on the left. Make sure your Configuration is set correctly - it should be debug for this example.
- In the Conditional compilation symbols text box enter: /define DEBUG
- Save the configuration and close the properties window.
- In your code, where you want to run a commands depending on the current build:
#if (DEBUG) Console.WriteLine("You'll only see me in debug mode..."); #endif
- Then give it a quick compile and witness the magic!
This is possibly a very basic trick that everyone has been using for years, but I’ve only recently been making the most of it.
If you’ve used this before - in what context do you employ it?
