Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usage of #if DEBUG pre-processor directive in C#? When must we use this?

What is the usage of #if DEBUG pre-processor directive in C#? When must we use this?

like image 379
masoud ramezani Avatar asked May 18 '10 11:05

masoud ramezani


3 Answers

In Debug mode:

#if DEBUG
            System.Console.WriteLine("Debug version");
#endif
            System.Console.WriteLine("Output");

Output as

Debug version
Output

In Release mode:

#if DEBUG
            System.Console.WriteLine("Debug version");
#endif
            System.Console.WriteLine("Output");

Output as

   Output

read this: #if (C# Reference)

Usage: If you have a set of values to be tested in the debug mode and not in the release mode you can use #if DEBUG

like image 51
anishMarokey Avatar answered Nov 17 '22 08:11

anishMarokey


You might feel more comfortable with the Conditional attribute, which can be used to exclude entire methods, without needing to complicate the source with conditionals on the calling side:

[Conditional("DEBUG")]
void Foo()
{
}

Foo() can be safely called in both debug and release - however in release mode, it would be a no-op.

like image 18
stusmith Avatar answered Nov 17 '22 08:11

stusmith


You don't have to use it at all. The purpose of it is to have sections of code that only get compiled in debug mode. e.g. you might have some code that enabled a master user, that could pretend to be any other user in the system for testing and debug pruposes. You would not want that user enabled in the release code for security reasons so you waould wrap the relevent sections of code in #if DEBUG and they would be excluded from release code.

like image 5
Ben Robinson Avatar answered Nov 17 '22 06:11

Ben Robinson