How to use #if..#elif…#else…#endif directives in C#?

CsharpProgrammingServer Side Programming

All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;).

#if

The #if directive allows testing a symbol or symbols to see if they evaluate to true.

#else

It allows to create a compound conditional directive, along with #if.

#elif

It allows creating a compound conditional directive.

#endif

The #endif specifies the end of a conditional directive.

The following is an example showing the usage of #if, #elif, #else and #endif directives −

Example

 Live Demo

#define One
#undef Two

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         #if (One && TWO)
         Console.WriteLine("Both are defined");
         #elif (ONE && !TWO)
         Console.WriteLine("ONE is defined and TWO is undefined");
         #elif (!ONE && TWO)
         Console.WriteLine("ONE is defined and TWO is undefined");
         #else
         Console.WriteLine("Both are undefined");
         #endif
      }
   }
}

Output

Both are undefined
raja
Published on 09-Aug-2018 06:58:03
Advertisements