CSharp - Preprocessor Directives Introduction


Preprocessor directives gives compiler additional information about code.

The following code shows how to use #if and #endif preprocessor directives.

Those conditional directives provide a way to include or exclude regions of code from compilation.

For example:

#define DEBUG
class MyClass
       void Test()
         #if DEBUG
            int x;
            Console.WriteLine ("Testing: x = {0}", x);

If we remove the DEBUG symbol, the statement is not compiled.

The statement in Test is compiled conditionally dependent upon the presence of the DEBUG symbol.

With the #if and #elif directives, you can use the ||, &&, and ! operators to perform or, and, and not operations on multiple symbols.

The following directive instructs the compiler to include the code that follows if the TESTMODE symbol is defined and the DEBUG symbol is not defined:


Preprocessor symbols can be defined within a source file.

And we can also set them with the /define:symbol command-line option.

#error and #warning symbols prevent accidental misuse of conditional directives by making the compiler generate a warning or error given an undesirable set of compilation symbols.

The following table lists the preprocessor directives.

Preprocessor directive
#define symbol
Defines symbol
#undef symbol
Undefines symbol
#if symbol [operator sym

symbol to test
operators are ==, !=, &&, and || followed by #else, #elif,
and #endif
Executes code to subsequent #endif
#elif symbol [operator sym
Combines #else branch and #if test

Ends conditional directives
#warning text
text of the warning to appear in compiler output
#error text
text of the error to appear in compiler output
#pragma warning [disable
| restore]
Disables/restores compiler warning(s)

#line [ number ["file"] |

number specifies the line in source code; file is the filename to
appear in computer output; hidden instructs debuggers to skip
over code from this point until the next #line directive
#region name
Marks the beginning of an outline
Ends an outline region