Separate Debug and Release code in C#

Use separate code for debug and release compilation in C#

  • Share

Basic functionality of your code does what it should do regardless of whether it is compiled in Debug of Release mode. Only differences might be related to debugging the code and tracing errors during debug.

For sure you want more monitoring during the development (debug mode), so you would probably add some sort of logging.

You can easily do this with C# pre-processing instructions

  // Debug work here
  // Release work here

These instructions can be used anywhere in code and everything in DEBUG condition part will be executed in debug mode compiled code, otherwise release code snippet will be executed.

This is really useful as you do not need to cleanup or comment lines of code you might want to use only during development (in debug mode).

Even for maintenance, you do not need to change any line of code to trace eventual errors that might have occurred during exploitation of code. Al you have to do is to normally debug code and you'll have all your tracing and logging available.

Vs Config

However, there is a small problem with this approach.

Code in the section which is different than current compiling mode will not be checked during compiling. In other words, your RELEASE code will not be checked for errors when you are compiling your code in DEBUG mode.

Other way to to execute different code for debug and release mode is to use method attributes to mark your method for executing in debug or release mode.

    private void MyDebugMethod()
        //Debug code

This is a normal method and code withing it will be checked on every build regardless of compile mode.

It can be easily test with simple console application

    class Program
        static void Main(string[] args)
        private static void MyDebugMethod()
            Console.Write("DEBUG MODE ON");

If you start this console application from Visual Studio in debug mode, you will see the message "DEBUG MODE ON". If you change Solution Configuration to release, this message will not be written in a console, meaning that that part of code was not reached. It was actually replaced by NOP (non meaningful operation), an empty operation that does nothing.


  • Share


Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus