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); #endif } ... }
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:
#if TESTMODE && !DEBUG
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 | Action |
---|---|
#define symbol | Defines symbol |
#undef symbol | Undefines symbol |
#if symbol [operator sym bol2]... | symbol to test operators are ==, !=, &&, and || followed by #else, #elif, and #endif |
#else | Executes code to subsequent #endif |
#elif symbol [operator sym bol2] | Combines #else branch and #if test |
#endif | 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"] | hidden] | 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 |
#endregion | Ends an outline region |