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

using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int i;
do
{
i = rnd.Next(0, 1000);
#if DEBUG
Console.WriteLine("number: " + i);
#endif
} while (i != 1);
}
}
}
view raw RandDebug.cs hosted with ❤ by GitHub

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")]


using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
PrintDebug();
}
[Conditional("Debug")]
static void PrintDebug()
{
Console.WriteLine("Debugging!");
}
}
}
view raw CondDebug.cs hosted with ❤ by GitHub
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.



No comments:

Post a Comment