Sunday, April 30, 2006

Use of conditional attributes in .NET

Attribute Conditional serves for creation of conditional methods, i.e. methods which are carried out only when the parameter of attribute is the symbolical constant certain by the instruction *define or is registered in properties the project.
Simple example. A conclusion of the message about trial version and about the registered version depending on attribute.

Open new Console Project.

Add a reference
using System.Diagnostics;

Add 2 methods to class:
[Conditional ("TRIAL")]
public static void Remind()
{
  Console.WriteLine("Please register your version!" );
  Console.ReadLine();
}
and

[Conditional ("FINAL")]

public static void Hello()

{
  Console.WriteLine("Thanks for registration!");
  Console.ReadLine();
}

Add to project properties -> Build -> Conditional compilation constants :

DEBUG;TRACE; TRIAL "COLOR: #ff0000">or DEBUG;TRACE; FINAL
Compile and Run.

No comments: