Saturday, 10 August 2013

Debugging in C# using #if DEBUG and [Conditional("DEBUG")]

1.  Configuring Debug/Release build

You can set condition on certain code blocks to only execute on debug mode. This does not mean running Debug (F5), but building the solution as a debug build rather than a release build. The type of build can be set in Build -> Configuration Manager;


When the solution is build in release mode, codes surrounded by #if DEBUG and #endif will be ignored. Similarly, if a method is marked as [Conditional("DEBUG")], it will be ignored, too.

2. Using #if DEBUG


Simply surround the code you want to execute only in Debug build in #if Debug and #endif. In the example above, Console.WriteLine("number: " + i); will be ignored in Release build, and the program will not  print anything. In certain IDEs, you will see the ignored part of the code gets greyed out. 

Variables introduced within the region will not be accessible from outside. (It will give you a compile error)


3. Using [Conditional("Debug")]


Marking a method with [Conditional("Debug")] will not be called on Debug build. It produces a cleaner code since it does need any markers around the method caller, and the behaviour is taken care of automatically depending on the build type.
[Conditional("Debug")] requires System.Diagnostics library.