.NET Tip of The Day
Learn one new .NET trick every day
Быстрое пополнение счета телефона      Login or Join

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.

7/27/2007
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.