Export (0) Print
Expand All
35 out of 43 rated this helpful - Rate this topic

#if

#if lets you begin a conditional directive, testing a symbol or symbols to see if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive.

#if symbol [operator symbol]...

where:

symbol
The name of the symbol you want to test. You can also use true and false. symbol can be prefaced with the negation operator. For example, !true will evaluate to false.
operator (optional)
You can use the following operators to evaluate multiple symbols:

== (equality)

!= (inequality)

&& (and)

|| (or)

You can group symbols and operators with parentheses.

Remarks

#if, along with the #else, #elif, #endif, #define, and #undef directives, lets you include or exclude code based on the condition of one or more symbols. This can be most useful when compiling code for a debug build or when compiling for a specific configuration.

A conditional directive beginning with a #if directive must explicitly be terminated with a #endif directive.

Example

// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
{
   public static void Main() 
   {

      #if (DEBUG && !VC_V7)
         Console.WriteLine("DEBUG is defined");
      #elif (!DEBUG && VC_V7)
         Console.WriteLine("VC_V7 is defined");
      #elif (DEBUG && VC_V7)
         Console.WriteLine("DEBUG and VC_V7 are defined");
      #else
         Console.WriteLine("DEBUG and VC_V7 are not defined");
      #endif
   }
}

Output

DEBUG and VC_V7 are defined

See Also

C# Preprocessor Directives

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.