Other Preprocessor Directives

A few other preprocessor directives are available in C# that are not found in Visual Basic .NET. This section discusses these additional directives, tells how they work, and shows what they can provide for you.

#undef

#undef is the exact opposite of #define. It removes the definition of a preprocessor constant. Listing 5.7 shows an example of how it is used.

Listing 5.7. Using #undef
#define MYDEBUG 

public void MyFunction() 
{
#if MYDEBUG 
    Response.Write("Hello"); 
#endif 

#undef MYDEBUG 

#if MYDEBUG 
    Response.Write("You won't see me!"); 
#endif 
} 

If you called the MyFunction function, you would get an output of Hello but not You won't see me!. Because MYDEBUG has been defined, the first Response.Write will be compiled in and executed. However, immediately afterward, the MYDEBUG symbol is undefined, so the second #if check will fail; the second Response.Write will not be compiled into the program and, therefore, will not be executed.

This can be useful if you need to temporarily remove a line or two inside a debugging function.You could simply #undef the symbol for the lines that you want to execute and then again #define the symbol where you want to restart the execution of the function.

#warning and #error

#warning and #error are very similar, so they are demonstrated together here. These two directives enable you to display a message to the user in the output window as the program is compiling. This message can have either a warning status or an error status. Listing 5.8 shows an example of each.

Listing 5.8. #warning and #error Example
#define MYDEBUG 

#if MYDEBUG && !DEBUG 
#error Both MYDEBUG and RELEASE are defined!! 
#elif MYDEBUG 
#warning WARNING - MYDEBUG is defined! 
#endif 

In this example, if you were in a debug build with MYDEBUG defined, you would simply see a warning telling you that MYDEBUG was defined while compiling your program. This is just a handy hint. However, if you switched your build configuration to a release build and built the program, you would get a compiler error with the text stated because both MYDEBUG and RELEASE were defined and DEBUG was not. This would be very useful to ensure that you do not compile any of your own debugging code into your release application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset