< Day Day Up > |
2.5. C# Preprocessing DirectivesPreprocessing directives are statements read by the C# compiler during its lexical analysis phase. They can instruct the compiler to include/exclude code or even abort compilation based on the value of preprocessing directives. A preprocessor directive is identified by the # character that must be the first nonblank character in the line. Blank spaces are permitted before and after the # symbol. Table 2-8 lists the directives that C# recognizes.
The three most common uses for preprocessing directives are to perform conditional compilation, add diagnostics to report errors and warnings, and define code regions. Conditional CompilationThe #if related directives are used to selectively determine which code is included during compilation. Any code placed between the #if statement and #endif statement is included or excluded based on whether the #if condition is true or false. This is a powerful feature that is used most often for debug purposes. Here is an example that illustrates the concept: #define DEBUG using System; public class MyApp { public static void Main() { #if (DEBUG) Console.WriteLine("Debug Mode"); #else Console.WriteLine("Release Mode"); #endif } } Any #define directives must be placed at the beginning of the .cs file. A conditional compilation symbol has two states: defined or undefined. In this example, the DEBUG symbol is defined and the subsequent #if (DEBUG) statement evaluates to true. The explicit use of the #define directive permits you to control the debug state of each source file. Note that if you are using Visual Studio, you can specify a Debug build that results in the DEBUG symbol being automatically defined for each file in the project. No explicit #define directive is required. You can also define a symbol on the C# compile command line using the /Define switch: csc /Define:DEBUG myproject.cs Compiling code with this statement is equivalent to including a #Define DEBUG statement in the source code. Diagnostic DirectivesDiagnostic directives issue warning and error messages that are treated just like any other compile-time errors and warnings. The #warning directive allows compilation to continue, whereas the #error terminates it. #define CLIENT #define DEBUG using System; public class MyApp { public static void Main() { #if DEBUG && INHOUSE #warning Debug is on. #elif DEBUG && CLIENT #error Debug not allowed in Client Code. #endif // Rest of program follows here In this example, compilation will terminate with an error message since DEBUG and CLIENT are defined. Code RegionsThe region directives are used to mark sections of code as regions. The region directive has no semantic meaning to the C# compiler, but is recognized by Visual Studio.NET, which uses it to hide or collapse code regions. Expect other third-party source management tools to take advantage of these directives. #region // any C# statements #endregion |
< Day Day Up > |