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. 

Comments (4)

  1. 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:

  2. 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:

  3. 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:

  4. Kris says:

    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?