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

Advertisement

#172 – Nested if Statements

The statement to be executed when an if statement’s boolean expression resolves to true can be another if statement.

            if (bob.IsSingle)
                if (TheGameIsOnToday())
                    WatchGame();
                else
                    PlayVideoGames();

Because the inner if/else is a single statement, it can follow the boolean expression of the outer if as the single statement to execute if the expression resolves to true.

This might lead to some confusion about which if statement the else applies to.  An else clause belongs to the last if that doesn’t have an else clause.

You could make this logic more clear by enclosing the inner if/else in braces.

            if (bob.IsSingle)
            {
                if (TheGameIsOnToday())
                    WatchGame();
                else
                    PlayVideoGames();
            }
            else
                DoWhateverWifeSays();

#170 – The else Portion of an if Statement

An if statement can optionally include an else keyword and block of statements, which will execute if the boolean expression for the if statement evaluates to false.

            if (age >= 50)
            {
                Console.WriteLine("Hey, you should consider joining AARP!");
                DisplayDetailsOfAARPMembership();
            }
            else
            {
                Console.WriteLine("You're still a young pup");
                DisplayInfoAboutVideoGames();
            }

#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