Friday, May 1, 2009

Determine Debug Mode in .NET

If you will ever need to execute different code paths for the Debug mode and the Release mode, this is the best way to do it.

You may also find this article very useful: Identifying the Run-Time and the Design Mode. It refers to UserControl's and Form's design mode.

Pre-processor directives

Visual Studio automatically generates a pre-processor directive called DEBUG which is linked to the mode you run your application in. All these directives are case sensitive! Pre-processor directives can be defined using #define (making the directive true) and #undef (making it false) in C#. You can check for any defined directive using the #if ... #else ... #endif statement.

Visual Studio IDE is even able to even grey out the code that will not be compiled regarding the current selected directive: DEBUG or RELEASE. This way you are aware, by a simple look, of which code is about to be used when the application is started.

Debug mode

If the DEBUG mode is currently selected, this is how our test code will look like. Please note the grey line!

C# .NET

string value = String.Empty;

 

#if (DEBUG)

    value = "DEBUG value";

#else

    value = "RELEASE value"; // This will not be executed!

#endif

Release mode

If the RELEASE mode is currently selected, this is how our test code will look like. Please note the grey line which is different now from the one on DEBUG mode!

C# .NET

string value = String.Empty;

 

#if (DEBUG)

    value = "DEBUG value"; // This will not be executed!

#else

    value = "RELEASE value";

#endif



kick it on DotNetKicks.com

3 comments:

Ian said...

Simple but very helpful! Thank you!

Michael Freidgeim said...

You can check assembly using ildasm or Reflector
See http://www.codeproject.com/Articles/72504/NET-Determine-Whether-an-Assembly-was-compiled-in

Michael Freidgeim said...

See also http://stackoverflow.com/questions/194616/how-to-tell-if-net-app-was-compiled-in-debug-or-release-mode/