#502 – #define and #undef Scope

When you include a #define or #undef preprocessor directive in a file, the scope in which that conditional symbol is defined (or not defined) is limited to that single file.

For example, suppose that we define the symbol QUIET within a file that creates an instance of a Dog and then calls the Bark method of the Dog object.

// Code from Program.cs
#define QUIET

using System;
using DogLibrary;

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

Let’s also suppose that the Dog.Bark method, which exists in a separate file, compiles differently depending on whether the symbol QUIET is defined.

// Code from Dog.cs
        public void Bark()
        {
#if QUIET
            Console.WriteLine("Arf");
#else
            Console.WriteLine("WOOOOOF!");
#endif
        }

Because QUIET is defined in Program.cs but not in Dog.cs, the Bark method will use the second (not quiet) line.

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: