Using &if and [Conditional()] to Keep Debug Code Under Control

The #if directive provides a perfect way to ensure your released executable doesn't execute any code that was only intended for debug mode.

#if (<symbol>) will return true whenever the symbol being checked has been defined by default, or manually using #define.

  //Perform debug only code
  //Release-level code

Remember, this is only one application of #if, you can use it any time you need to check to see if a symbol has been defined.

You can also use the [Conditional("<symbol>")] attribute on any method that has a return type of void. This will cause the compiler to remove all calls to the given method if the specified symbol is not defined.

/* using System.Diagnostics; */
public void printDebug() {
  Console.WriteLine("Debug Information");

Now printDebug() will not be executed unless the application is in debug mode.

Either method will save you time and effort by allowing you to leave debug code in your application, as well as provide you a more standardized and safe way to include debug code.

Creative Commons License

What do you think?