4.9 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
class MyClass {
  int x;
  void Foo( ) {
  # 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 they can be passed to the compiler with the /define: symbol command-line option. All preprocessor symbols are implicitly true, so the #define statement in the previous example is effectively the same as the following:

#define DEBUG = true

The #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. See Table 4-3 for a list of preprocessor directives and their actions.

Table 4-3. Preprocessor directives

Preprocessor directive


#define symbol

Defines symbol.

#undef symbol

Undefines symbol.

#if symbol [operator symbol2] ...

symbol to test.

operators are = =, !=, &&, || followed by #else, #elif, and #endif.


Executes code to subsequent #endif.

#elif symbol [operator symbol2]

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.

#line [ number ["file"] | hidden]

number specifies the line in source code; file is the filename to appear in computer output; hidden specifies that the compiler should generate debugger information (this feature was added in Visual C# 2003).

#region name

Marks the beginning of outline.

#end region

Ends an outline region.

    Part II: Programming with the .NET Framework
    Part IV: API Quick Reference