Conditional Methods in C#

Posted: April 20, 2011 in .NET
Tags: , , , , ,

Sometimes when you are developing/debugging an application you may want a different behavior than the release/retail build. The conditional attribute in .NET let’s you do this.

Let us suppose that we have a method that loads data into an object from a remote source like a database. While debugging, you may need to restart the application many times to test different methods or changes. If it takes more than a couple of seconds to load your data, you may want to temporarily cache this data. Since your application needs real-time data in the production environment, the conditional attribute is an easy way to tell the compiler to only call our cache loader while in the DEBUG configuration.

This article is not about how to cache data, but rather how to define a method that is only called when using the debug configuration. In my experience, cached data represents a good opportunity to useĀ the conditionalĀ attribute. There are many other situations where this would be helpful.

In this example method, I have applied the the conditional attribute, [Conditional("DEBUG")], so that the data is only cached when ‘DEBUG’ is defined. When running the app in Visual Studio, ‘Debug’ can be selected in the active configuration list. This will define debug during compilation for you.

///
/// This method is only called when DEBUG is defined
///
[Conditional("DEBUG")]
private void CacheIfDebug()
{
if (File.Exists(@"C:\cachedPSDFileData.xml"))
{
entireFileTree = XElement.Load(@"C:\cachedPSDFileData.xml");
}
else
{
setEntireFileTree();
entireFileTree.Save(@"C:\cachedPSDFileData.xml");
}
}

In the example below, when using the ‘Debug’ configuration, both methods will execute. When using ‘Release’ configuration, only the second method will be called. Since the ‘CacheIfDebug’ method has been decorated with the conditional attribute, the compiler removes references to it. For this reason, methods decorated with the conditional attribute must be ‘void’ return type.

private void DoSomething()
{
CacheIfDebug();
DoSomethingElse();
}

Using the conditional attribute makes it easy to debug and deploy without changing your code for each environment.
For more information about the conditional attribute check out these links.

http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx

http://community.bartdesmet.net/blogs/bart/archive/2006/08/30/4368.aspx

About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s