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

{      …


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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: