Feb 20
2010

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

Written by Robert Greiner | posted in Programming, Tips and Tricks | View Comments

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.

#if DEBUG
	//Perform debug only code
#else
	//Release-level code
#endif

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; */
[Conditional("DEBUG")]
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.

Comments are closed.

blog comments powered by Disqus
.NET Algorithmic Art ASP ASP .NET ASP .NET MVC audio Bill Gates C# code review Computational Art CouchDB CSS Database DateTime debug DevDays eclipse ethics FileSystem Git Improvement iPhone Java JQuery Knopflerfish Layouts mail Microsoft Oracle OSGi Processing Python Ruby SMTP SOA Software Piracy Source Control SQL StackOverflow tools TortoiseGit training Web Standards Windows XHTML