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:

  • #define and #undef are used to define and undefine, respectively, conditional compilation symbols.

  • #if , #elif , #else , and #endif are used to conditionally skip sections of source code.

  • #error and #warning are used to display errors and warnings, respectively.

  • #region and #endregion are used to mark sections of source code.

  • #line is used to control line numbers for errors and warnings.

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.

FOR C++ PROGRAMMERS

In C++, preprocessor directives are evaluated in a preliminary run-through of your code first, and then the code itself is compiled. In C#, on the other hand, all this takes place in the same pass through your code (in fact, it's not "preprocessing" at all).

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!

Категории