This documentation is archived and is not being maintained.


Marks a conditional method whose execution depends on a specified preprocessing identifier.



A string representing the name of a preprocessing identifier.

Applies To

Method declarations.


The Conditional attribute is a multiuse attribute. Conditional is an alias for System.Diagnostics.ConditionalAttribute.

Wherever a conditional method is called, the presence or absence of the preprocessing symbol specified by conditionalSymbol at the point of the call determines whether the call is included or omitted. If the symbol is defined, the call is included; otherwise, the call is omitted. Conditional methods provide a cleaner, more elegant alternative to enclosing the method call in #if conditionalSymbol...#endif preprocessor directives.

A conditional method must be a method in a class or struct declaration and must have a return type of void (for other restrictions, see 17.4.2 The Conditional attribute).

If a method has multiple Conditional attributes, a call to the method is included if at least one of the conditional symbols is defined (in other words, the symbols are logically ORed together).

[Conditional("A"), Conditional("B")] public static void IfAorB( ) 

To achieve the effect of logically ANDing symbols, you can define serial conditional methods:

[Conditional("A")] public static void IfAandB( ) 
   AandBPrivate( ); 
[Conditional("B")] static void AandBPrivate( ) 
   /* Code to execute when both A and B are defined... */

Call IfAandB; if both A and B are defined, AandBPrivate will execute.


// cs_attribute_conditional.cs
#define DEBUG
using System;
using System.Diagnostics;
public class Trace 
   [Conditional("DEBUG")] public static void Msg(string msg) 
class Test 
   static void A( ) 
      Trace.Msg("Now in A.");
      B( );
   static void B( ) 
      Trace.Msg("Now in B.");
   public static void Main( ) 
      Trace.Msg("Now in Main.");
      A( );


Now in Main.
Now in A.
Now in B.

If you compile the sample with first line omitted (or changed to #undef DEBUG), the output will be: Done..

See Also

C# Attributes | Conditional Methods Tutorial | C# Preprocessor Directives