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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
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")]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
PrintDebug(); | |
} | |
[Conditional("Debug")] | |
static void PrintDebug() | |
{ | |
Console.WriteLine("Debugging!"); | |
} | |
} | |
} |
[Conditional("Debug")] requires System.Diagnostics library.