Preprocessor - #if


The directives #if and #endif conditionally enable blocks of code to be included in the compilation. The determination is made based upon whether an expression involving one or more symbols evaluates to true. The general form of #if is as follows.

#if symbol-expression
  statements
#endif

When symbol-expression evaluates to true, the code enclosed between the #if and the #endif is included in the compilation. When symbol-expression evaluates to false the code is ignored by the compiler.

A symbol expression may just be the name of a symbol. The operators !, ==, !=, && and || may also be used. Parentheses are allowed.

The following program makes use of conditional compilation.

// Preprocessor1 - #define, #if, #endif

#define Symbol

using System;

class Program
{
    static void Main()
    {
#if Symbol
            Console.WriteLine("Symbol defined");
#endif
    }
}

Because Symbol is defined, the Console.WriteLine is included in the compilation. If Symbol were not defined (by removing the associated #define from the program) the code would be bypassed. Another example involving an expression is shown below.

// Preprocessor2 - #define, #if, #endif

#define Symbol1
#define Symbol2

using System;

class Program
{
    static void Main()
    {
#if Symbol1
        Console.WriteLine("Symbol1 defined");
#endif

#if Symbol1 && Symbol2
        Console.WriteLine("Symbol1 and Symbol2 defined");
#endif
    }
}

The program prints the following.

Symbol1 defined
Symbol1 and Symbol2 defined