Thursday, 29 June 2017

Conditional Attribuite

sometimes you may want to run a method only in DEBUG mode, or some other defined condition. if you run the following console app in debug

using System;
using System.Diagnostics;

namespace ConditionalAttributeExample
{
    class Program
    {
        static void Main(string[] args)
        {
            DebugMethod();
            HelloWorld();
        }

        [Conditional("DEBUG")]
        public static void DebugMethod()
        {
            Console.WriteLine("Running in Debug");
        }

        public static void HelloWorld()
        {
            Console.WriteLine("Hello World");
        }
    }
}

You'll get



but in release



 Now if you wanted to create a method that only runs in release you'll quickly learn that there is no RELEASE preprocessor directive, so you'll have to add your own, you can configure it in your project properties, but that's not obvious enough for me. Instead I like to define one at the top of my file:

#define RELEASE
#if DEBUG
#undef RELEASE
#endif

using System;
using System.Diagnostics;

namespace ConditionalAttributeExample
{
    class Program
    {
        static void Main(string[] args)
        {
            DebugMethod();
            ReleaseMethod();
            HelloWorld();
        }

        [Conditional("DEBUG")]
        public static void DebugMethod()
        {
            Console.WriteLine("Running in Debug");
        }

        [Conditional("RELEASE")]
        public static void ReleaseMethod()
        {
            Console.WriteLine("Running in Release");
        }

        public static void HelloWorld()
        {
            Console.WriteLine("Hello World");
        }
    }
}

you can also chain conditional attributes together, so the following

[Conditional("RELEASE"), Conditional("DEBUG")]
public static void ReleaseOrDebugMethod()
{
    Console.WriteLine("Running in Release Or Debug");
}

is completely valid and if the ReleaseOrDebugMethod() is called from the main it'll fire in both the release or Debug Versions.