Preprocessor Directives

Preprocessor directives supply the compiler with additional information about regions of code. The most common preprocessor directives are the conditional directives, which provide a way to include or exclude regions of code from compilation. For example:

#define DEBUG
using System;
class MyClass {
  static int x = 5;
  static void Main( ) {
  # if DEBUG
    Console.WriteLine("Testing: x = {0}", x);
  # endif
  }
}

In this class, the statement in Foo is compiled as conditionally dependent upon the presence of the DEBUG symbol. If we remove the DEBUG symbol, the statement is not compiled. Preprocessor symbols can be defined within a source file (as we have done) and can be passed to the compiler with the /define: symbol command-line option.

The #error and #warning symbols prevent accidental misuse of conditional directives by making the compiler generate a warning or error when given an undesirable set of compilation symbols. See Table 1-5 for a list of preprocessor directives and their actions.

Table 1-5. Preprocessor directives

Preprocessor directive

Action

#define symbol

Defines symbol

#undef symbol

Undefines symbol

#if symbol [ operator symbol2 ] ...

symbol to test; operators are ==, !=, &&, and ||, followed by #else, #elif, and #endif

#else

Executes code to subsequent #endif

#elif symbol [ operator symbol2 ]

Combines #else branch and #if test

#endif

Ends conditional directives

#warning text

text of the warning to appear ...

Get C# Language Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.