only for RuBoard - do not distribute or recompile Previous Section Next Section

2.18 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 {
  int x;
  public void Foo(  ) {
  # if DEBUG
  # warning "Debug mode is ON"
    Console.WriteLine("Testing: x = {0}", x);
  # endif
  }
}

In this class, the statement in Foo is compiled conditionally, dependent upon the presence of the user-selected DEBUG symbol. If you remove the DEBUG symbol, the statement isn't compiled. Preprocessor symbols can be defined within a source file as just shown 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 given an undesirable set of compilation symbols.

2.18.1 Preprocessor Directives

The C# language supports the preprocessor directives shown in Table 2-4.

Table 2-4. Preprocessor directives

Preprocessor directive

Action

#define symbol

Defines symbol

#undef symbol

Undefines symbol

#if symbol [operator symbol2] ...

symbol to test; operator: ==, !=, &&, || followed by #else, #elif, #endif

#else

Executes code to subsequent #endif

#elif symbol [operator symbol2]

Combines #else branch and #if test

#endif

Ends conditional directives

#warning text

text: warning text to appear in compiler output

#error text

text: error message to appear in compiler output

#line number [file]

number specifies line in source code; file is the filename to appear in computer output

#region name

Marks beginning of outline

#end region

Ends an outline region

only for RuBoard - do not distribute or recompile Previous Section Next Section