What is a conditional pre-processor directive in C#?

CsharpProgrammingServer Side Programming

Use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive.

Here is the syntax −

#if symbol [operator symbol]...

Here, symbol is the name of the symbol you want to test. You can also use true and false or prepends the symbol with the negation operator.

The operator symbol is the operator used for evaluating the symbol. Operators could be either of the following −

  • == (equality)
  • != (inequality)
  • && (and)
  • || (or)

Here is an example showing the usage of conditional pre-processor directives in C# −

Example

 Live Demo

#define DEBUG
#define VC_V10
using System;

public class Demo {
   public static void Main() {
      #if (DEBUG && !VC_V10)
      Console.WriteLine("DEBUG is defined");
      #elif (!DEBUG && VC_V10)
      Console.WriteLine("VC_V10 is defined");
      #elif (DEBUG && VC_V10)
      Console.WriteLine("DEBUG and VC_V10 are defined");
      #else
      Console.WriteLine("DEBUG and VC_V10 are not defined");
      #endif
      Console.ReadKey();
   }
}

Output

DEBUG and VC_V10 are defined
raja
Published on 09-Aug-2018 12:38:39
Advertisements