How to conditional attribute in C# code

Description

The Conditional Attribute allows you to create conditional methods. A conditional method is invoked only when a specific symbol has been defined via #define. Otherwise, the method is bypassed.

A conditional method offers an alternative to conditional compilation using #if. Conditional is another name for System.Diagnostics.ConditionalAttribute. To use the Conditional attribute, you must include the System.Diagnostics namespace.

Conditional methods have a few restrictions.

  • Conditional methods must return void.
  • Conditional methods must be members of a class, not an interface.
  • Conditional methods cannot be preceded with the override keyword.

Example 1

Example for C# Conditional Attribute


#define TRIAL /*w w  w .ja  v a 2s. c o  m*/
 
using System; 
using System.Diagnostics; 
 
class MainClass { 
 
  [Conditional("TRIAL")]  
  void trial() { 
    Console.WriteLine("Trial version, not for distribution."); 
  } 
 
  [Conditional("RELEASE")]  
  void release() { 
    Console.WriteLine("Final release version."); 
  } 
 
  public static void Main() { 
    MainClass t = new MainClass(); 
 
    t.trial(); // call only if TRIAL is defined 
    t.release(); // called only if RELEASE is defined 
  } 
}

The code above generates the following result.

Example 2

Compile the following code with csc /define:DEBUG MainClass.cs


using System;// ww  w  . j  a  v a 2 s . c om
using System.Diagnostics;  

public class MyClass {

  [Conditional("DEBUG")]
  public void OnlyWhenDebugIsDefined( ) {
    Console.WriteLine("DEBUG is defined");
  }
}



public class MainClass {

  public static void Main( ) {

    MyClass f = new MyClass( );
    f.OnlyWhenDebugIsDefined( );
  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor