What is the usage of #if DEBUG
pre-processor directive in C#? When must we use this?
When compiling you can set Compiler flags which you can use to put code into those directives. That code will not be compiled and never ends up in the final assembly output. DEBUG is one of the predefined ones, but you can use your own.
As an example of usage: In one of the current developments we use a compiler flag to state whether to use A login mask to log in a user, or whether login should occur automatically with the current principal. The second mode is only for the developers to e.g. debug quicker without having to log in.
Another example: In some mono code you will see flags. In this case code may be compiled differently when e.g. targetting a different framework, as it uses classes that may not exist in earlier releases.
Related to this is the Conditional-Attribute with which you can mark a method. If said flag isn't set, calls to the method will not be performed. The method still ends up in the IL, but calls will be removed.
Check for example following code:
var mthods = typeof (Debug).GetMethods().Where(mi => mi.Name.Equals("WriteLine")).ToList();
var attribs = mthods[0].GetCustomAttributes(true);
You will notice that the Debug.WriteLine method has the Conditional attribute applied to it: Calls to it will be removed when you compile WITHOUT the DEBUG compiler flag.