#502 – #define and #undef Scope
January 20, 2012 Leave a comment
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.