C# #if Preprocessing Directive

In this chapter you will learn:

  1. How to use Preprocessing Directives #if
  2. Syntax for #if Preprocessing Directive
  3. Example for #if Preprocessing Directive
  4. Use #if with #else

Description

The #if and #endif directives enable conditional compilation. A symbol is true if it has been defined. A symbol is false if it has not been defined.

If a symbol has been defined by a #define directive, the symbol true.

Syntax

The general form of #if is


#if symbol-expression
   statement sequence 
#endif

Example 1


#define AAA//from   www .  j  av a  2  s. c  om
 
using System; 
 
class MainClass { 
  public static void Main() { 
     
    #if AAA
      Console.WriteLine("Compiled for experimental version."); 
    #endif 
   
    Console.WriteLine("This is in all versions."); 
  } 
}

The code above generates the following result.

Example 2

Use #if with #else


#define AAA //from   www. j av  a  2 s  . c o m
#define BBB 
 
using System; 
 
class Test { 
  public static void Main() { 
     
    #if AAA 
      Console.WriteLine("Compiled for AAA version."); 
    #else 
      Console.WriteLine("Compiled for release."); 
    #endif 
 
    #if AAA && BBB 
       Console.Error.WriteLine("Testing AAA and BBB version."); 
    #else 
       Console.Error.WriteLine("Not (AAA and BBB) version."); 
    #endif 
   
    Console.WriteLine("This is in all versions."); 
  } 
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Preprocessing Directive #elif
  2. Syntax for #elif Preprocessing Directive
  3. Example for #elif Preprocessing Directive
Home »
  C# Tutorial »
    C# Types »
      C# Preprocessor
C# preprocessor
C# #define Preprocessor
C# #if Preprocessing Directive
C# #elif Preprocessing Directive
C# #undef
C# #line directive
C# #region directive
C# #warning preprocessor