Conditional compilation with ConditionalAttribute

It is possible to conditionally compile code out of the final product, this is usually useful when you want to have extra checks in the code (asserts, invariant checking) during development and testing, in debug mode, but do not want to incur the cost of this checking in the final release product. Just put all of the checking into a method and place Conditional attribute on it.

public sealed class Debug

{      …

[Conditional(“DEBUG”)]

public static void Assert(bool condition, string message){

TraceInternal.Assert(condition, message);

}

}

What this actually does is tell the compiler to only call the method when the supplied preprocessor symbol is defined. The method will still be compiled and will still exist in the assembly. So, in a debug build a program that looks like this:

static void Main(string[] args){

Debug.Assert(true, “This condition must be true”);

}

will still look like that, but when compiled in release mode, will look like this:

private static void Main(string[] args){

}

Note: the Debug classe of the .NET Framework use the ConditionalAttribute. So you don’t have to worry about any performance hit whatsoever when you call various methods of this class as a debugging aid. These calls just won’t make it in the release build.