Csharp/CSharp Tutorial/Attribute/Conditional Attribute
Demonstrate the Conditional attribute
#define TRIAL
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
}
}
Trial version, not for distribution.
The Conditional Attribute
- 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.
10.3.Conditional Attribute 10.3.1. The Conditional Attribute 10.3.2. <A href="/Tutorial/CSharp/0200__Attribute/DemonstratetheConditionalattribute.htm">Demonstrate the Conditional attribute</a> 10.3.3. <A href="/Tutorial/CSharp/0200__Attribute/TheConditionalattributesettinginCompileparameter.htm">The Conditional attribute setting in Compile parameter</a>
The Conditional attribute setting in Compile parameter
// csc /define:DEBUG MainClass.cs
using System;
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( );
}
}