#504 – Using the #else Directive

You can conditionally compile code using the #if and #endif preprocessor directive.  You can also use an #else clause between the #if and the #endif.

In the code below, we’ve commented out the definition of DOGSBARK, so the code between the #else and #endif will be compiled.

//#define DOGSBARK

using System;
using DogLibrary;

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

Note that the code after the #if directive is greyed out, while the code after the #else is formatted normally.

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

#115 – Using #if, #else, #endif

When using the #if directive to conditionally compile code if a particular symbol is defined, you can also  using #else to conditionally compile code if the symbol is not defined.

Here’s an example:

#if LOGGING
    DoLotsOfLogging();   // To assist in debugging
#else
    DoMinimalLogging();
#endif