O'Reilly logo

C# Essentials by Peter Drayton, Ben Albahari, Brad Merrill

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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 they can be passed to the compiler with the /define : symbol command-line option. All preprocessor symbols are implicitly true, so the previous #define statement is effectively identical to:

#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.

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required