Programming, CakePHP and commentary from Britain.

Popular

CakePHP Livesearch
CakePHP Sessions
VBScript & Excel
VBScript & Oracle

Search

E-mail

kdobson@gmail.com

Subscribe

RSS 2.0

Posts Tagged ‘visual studio’

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.

  1. In Visual Studio select the Project menu and click “(Project) Properties” at the bottom of the menu.
  2. Select the Build tab on the left. Make sure your Configuration is set correctly - it should be debug for this example.
  3. In the Conditional compilation symbols text box enter: /define DEBUG
  4. Save the configuration and close the properties window.
  5. 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

  6. Then give it a quick compile and witness the magic!
There are a couple of uses that spring to mind - debug trace messages to help monitor what your code is doing, only deleting a file in release mode (if you’re downloading a file from the Internet repeatedly), outputting detailed exceptions in debug, but nice error messages in release.

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?