Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0221 Conditional compilation

C# uses the preprocessor directives to control the compilation. The preprocessor directives begin with # and it must appear on its own line. The preprocessor directives conditional compilation is #if, #else and, #endif, and #elif. The #if directive tells the compiler to ignore a section of code unless a specified symbol has been defined. To define a symbol we use the #define or set it in the compilation. #define directives must be at top of file. Symbol names are uppercase by convention. #define TESTMODE using System; class Program { static void Main() { #if TESTMODE Console.WriteLine("in test mode!"); // OUTPUT: in test mode! #endif } } The output: in test mode! To define a symbol assembly-wide, specify the /define switch when compiling: csc Program.cs /define:TESTMODE,ANOTHER Preprocessor directives C# statements #if if #else else #elif or #else #if else if The ||, &&, and ! operators can be used to perform or, and, and not operations. Logical Operators Supported by the #if..#endif Directive Operator Example Description == #if winXP == true Evaluates to true if the symbol winXP is defined. Equivalent to #if winXP. != #if winXP != true Evaluates to true if the symbol winXP is not defined. Equivalent to #if !winXP. && #if winXP && release Evaluates to true only if the symbols winXP and release are defined. || #if winXP || release Evaluates to true if either of the symbols winXP or release are defined. () #if (winXP || win7) && release Parentheses allow you to group expressions. Evaluates to true if the symbols winXP or win7 are defined and the symbol release is defined. The following code uses #define, #undef, #elif and #else to do the conditional compilation. #define win7 #define release #undef win2000 using System; using System.Diagnostics; class MainClass { [Conditional("DEBUG")] public static void DumpState() { Console.WriteLine("Dump some state..."); } public static void Main() { string platformName; #if winXP // Compiling for Windows XP platformName = "Microsoft Windows XP"; #elif win2000 // Compiling for Windows 2000 platformName = "Microsoft Windows 2000"; #elif win7 // Compiling for Windows 7 platformName = "Microsoft Windows 7"; #else // Unknown platform specified platformName = "Unknown"; #endif Console.WriteLine(platformName); } } To build the example and define the symbols winXP, use the command csc /define:winXP; Example.cs.