#503 – Conditionally Compile Code Using #if / #endif Directives

Once you define a conditional compilation symbol using the #define directive, you can use the #if directive to conditionally compile code when the corresponding conditional compilation symbol is defined.

In the code sample below, the Dog.Bark method is called, because the DOGSBARK symbol is defined and so the line containing the call to Bark is compiled.

#define DOGSBARK

using System;
using DogLibrary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Dog d1 = new Dog("Kirby", 12);
#if DOGSBARK
            d1.Bark();
#endif
        }
    }
}

If we don’t define the DOGSBARK symbol, then the compiler doesn’t compile the line between the #if and #endif directives.  In fact, since the compiler doesn’t even look at these lines in this case, they don’t even have to contain valid C# syntax.

#499 – Conditional Compilation Symbols Are Defined or Undefined

At any given point in your source code, while the compiler is compiling that section of code, a particular conditional compilation symbol is either defined or undefined.

You define a conditional compilation symbol

  • Using the #define preprocessor directive
  • Using the /define option on the compiler command line
  • Implicitly (for DEBUG and TRACE symbols), when selecting a build option for a project

You undefine a conditional compilation symbol

  • Using the #undef preprocessor directive
  • When reaching the end of a source file

A conditional compilation symbol is either defined or undefined–it has no value.

You check whether a conditional compilation symbol is defined by using the #if or #elif preprocessor directives.

A conditional compilation symbol remains defined in a source file until the end of the containing source file or until encountering an #undef directive (whichever comes first).