Microsoft Visual C#.NET 2003 Kick Start
The last topic discussed in this chapter is using preprocessor directives . These are directives to the compiler, not C# statements, and they enable you to skip compilation of sections of your code that you specify. Here are the C# preprocessing directives:
You can see an example in ch01_12.cs, Listing 1.12. In that example, it's the user 's birthday, so we'll display a birthday greeting. To do that, we define a symbol named Birthday and expressly undefine a symbol named NormalDay . Then we can use #if statements to indicate which code we want compiled and which we want to omit, and in this case, we'll only compile a statement to display the birthday greeting.
Listing 1.12 Using Preprocessor Directives (ch01_12.cs)
#define Birthday #undef NormalDay using System; class ch01_12 { static void Main() { #if Birthday Console.WriteLine("Happy Birthday!"); #else Console.WriteLine("It's not your birthday."); #endif #if NormalDay Console.WriteLine("It's just a normal day."); #endif } } Because we've defined the symbol Birthday , this code in Listing 1.12 makes the compiler compile the statement Console.WriteLine("Happy Birthday!"); , but not the statement Console.WriteLine("It's not your birthday."); :
#if Birthday Console.WriteLine("Happy Birthday!"); #else Console.WriteLine("It's not your birthday."); #endif When you compile ch01_12.cs, the only WriteLine statement that is actually compiled is Console.WriteLine("Happy Birthday!"); , so here's the result when you run this program:
C:\>ch01_12 sHappy Birthday! |