ConditionalAttribute in C#

The Conditional attribute which is an alias for ConditionalAttribute present in System.Diagnostics, makes the execution of a method dependent on a preprocessing identifier. It can be applied to a method or an attribute class. It tells the compiler to include the method or attribute, based on whether the identifier is defined or not. We can use the following methods to define the identifier :

  • Mention it in compiler command-line options (for example, /define:CustomConditionString).
  • Mention it in environment variables in the operating system shell (for example, set CustomConditionString=1).
  • Mention it in pragmas in the source code (for example, #define CustomConditionString to define the compilation variable and #undef CustomConditionString to undefine it).

Few things to keep in mind while using conditional attribute:

  • Conditional attribute can be used for methods present in a class or struct only.
  • The return type for the conditional method must be void.
  • A conditional method must not be marked with override modifier.
  • The conditional method must not be an implementation of an interface method.
  • #if and #endif directives also can do the same job as that of Conditional attribute.

This is how we can use the conditional attribute :

 #define CustomConditionString
 classProgram
 {
  static void Main(string[] args)
  {
   Foo();
  }

  [Conditional("CustomConditionString")]
  public static void Foo()
  {
   Console.WriteLine("Foo() called");
  }
 }

This will give an output. Whereas if we do not define the identifier “CustomConditionString”, then there will be no output.

 #define CustomConditionString
 #undef CustomConditionString
 classProgram
 {
  static void Main(string[] args)
  {
   Foo();
  }

  [Conditional("CustomConditionString")]
  public static void Foo()
  {
   Console.WriteLine("Foo() called");
  }
 }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s