Conditional Attribute

by Miguel de Icaza

One cute feature of C# 1.0 was the introduction of the Conditional attribute. When you apply the conditional attribute to a method, calls to this method are only included in the resulting code if the appropriate define is set.

For instance, consider:

	[Conditional ("DEBUG")]
	void Log (string format, params object [] args)
	{
		Console.WriteLine (String.Format (format, args));
	}
	

Calls to Foo.Log become no-ops unless you pass the -define:DEBUG command line option to the compiler.

What is interesting about this compiler-supported feature is that that the code inside the method Log is checked for errors during compilation as any other regular method. They are first class citizens.

Posted on 12 Jun 2010