Neat nuggets of .NET - The Conditional attribute

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")]staticprivatevoid method1(){Console.WriteLine("This only works in DEBUG mode.");}

[Conditional("custom")]staticprivatevoid 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.