C# Conditional Attribute

In this chapter you will learn:

  1. How to use conditional attribute
  2. Example for C# Conditional Attribute
  3. Conditional attribute setting in Compile parameter

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 /* ww w.j ava 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;/*from  w  ww . j av  a  2s  .  co  m*/
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.

Next chapter...

What you will learn in the next chapter:

  1. How to create your own attribute
  2. Retrieving a Specific Attribute and Checking Its Initialization
  3. A custom attribute based on bool value
Home »
  C# Tutorial »
    C# Types »
      C# Attribute
C# Attributes
C# Obsolete Attribute
C# Conditional Attribute
C# Custom Attributes
C# Attribute parameter
C# Attribute Usage
C# Attribute reflection