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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: