CSharp examples for Language Basics:Preprocessor
Use the #if, #elif, #else, and #endif preprocessor directives to identify blocks of code.
Use the System.Diagnostics.ConditionalAttribute attribute to define methods that should be called conditionally only.
Control the inclusion of the conditional code using the #define and #undef directives in your code.
Logical Operators Supported by the #if..#endif Directive
Operator | Example | Description |
---|---|---|
== | #if myFlag == true | Equality. Evaluates to true if the symbol myFlag is defined. Equivalent to #if myFlag. |
!= | #if myFlag != true | Inequality. Evaluates to true if the symbol myFlag is not defined. Equivalent to #if !myFlag. |
&& | #if myFlag && release | Logical AND. Evaluates to true only if the symbols myFlag and release are defined. |
|| | #if myFlag || release | Logical OR. Evaluates to true if either of the symbols myFlag or release are defined. |
() | #if (myFlag || win7) && release | Parentheses allow you to group expressions. Evaluates to true if the symbols myFlag or win7 are defined and the symbol release is defined. |
#define win7/*from w w w . ja va 2s . c o m*/ #define release #undef myValue using System; using System.Diagnostics; class MainClass { [Conditional("DEBUG")] public static void DumpState() { Console.WriteLine("Dump some state..."); } public static void Main() { // Declare a string to contain the platform name string platformName; #if myFlag // Compiling for Windows XP platformName = "Microsoft Windows XP"; #elif myValue // 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); // Call the conditional DumpState method DumpState(); } }