Welcome to MSDN Blogs Sign in | Join | Help

Neat nuggets of .NET - The Conditional attribute

Ever wanted different behavior between DEBUG and RELEASE builds?  But without having to fork your code or have to result to preprocessor directives?  Well let me introduce you to the Conditional attribute.

The Conditional attribute is simple: the method isn't executed unless a particular string is defined at compile time.  Let's look at an example:

using System.Diagnostics;

[
Conditional("DEBUG")]
static private void
method1()
{
   
Console.WriteLine("This only works in DEBUG mode."
);
}

[
Conditional("custom"
)]
static private void
method2()
{
   Console.WriteLine("This only works when 'custom' is defined"
);
}

By default Visual Studio defines "DEBUG" for debug builds, so method1 would work.  But method2 would be replaced with a noop unless "custom" was defined during the build process.  (You can add your custom symbols on the Build application designer page.)

This way you can change program behavior with a simple build flag, which can be extremely useful in certain situations. 

Published Thursday, July 07, 2005 3:50 PM by ChrSmith

Comments

Thursday, July 07, 2005 9:20 PM by Jónas Antonsson

# The conditional attribute

Chris Smith's latest blog entry reminded me of a really cool attribute - The Conditional Attribute. In short the attribute let's you manipulate code behaviour according to the build settings selected for your assembly. Here's the example from Chris Smith's blog:
Thursday, July 07, 2005 9:21 PM by Jónas Antonsson

# The conditional attribute

Chris Smith's latest blog entry reminded me of a really cool attribute - The Conditional Attribute. In short the attribute let's you manipulate code behaviour according to the build settings selected for your assembly. Here's the example from Chris Smith's blog:
Thursday, July 07, 2005 9:22 PM by Jónas Antonsson

# The conditional attribute

Chris Smith's latest blog entry reminded me of a really cool attribute - The Conditional Attribute. In short the attribute let's you manipulate code behaviour according to the build settings selected for your assembly. Here's the example from Chris Smith's blog:
Thursday, July 07, 2005 9:27 PM by Kris

# re: Neat nuggets of .NET - The Conditional attribute

I have recently looked into this. I wished I could do this:

[Conditional("QA")]
static private boolean IsAdmin()
{
return true;
}

[Conditional("RELEASE")]
static private boolean IsAdmin()
{
checkInAD(...)
}

Some code just calls
if (IsAdmin())
{
RestartApp();
}

Same method but only one of them is chosen during compilation based on your setting. That way I could have a totally different implementation in the qa builds to test some specific stuff which is highly dependent on the AD roles. Any ideas?

New Comments to this post are disabled
 
Page view tracker