How to use Preprocessing Directives #if

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 w w w  . j ava 2 s . co m*/
 
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  ava2 s .  co 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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor