#503 – Conditionally Compile Code Using #if / #endif Directives
January 23, 2012 1 Comment
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.
The part that I don’t understand is using #define will define the symbol and it will make it evaluate true all the times if used in a #if, what’s the point to use it on a #if if it will always be TRUE! 🙂
I must not be getting this right … Again, #define will make the symbol be true all the times, mine as well not use #if at all … not sure I get it. Please help me understand it.