ConditionalAttribute

Eric Gunnerson has posted about the ConditionalAttribute attribute and its use, in comparison to the #if directive.
In his example, he has two methods, each is called from a third method. The call to the first is in a #if DEBUG block and the second method is marked with a Conditional(“DEBUG”) attribute. He then says that neither call will be made if DEBUG is not defined.

This is true (not that he needs my approval ;).

Here’s a riddle for you all. What is the difference between the two following code segments, both at compile time and at run time (considering DEBUG is defined/not defined for each case):

  1. public class Program
    {
        public static void Main(string[] args)
        {
            CallMethod();
        }

        [Conditional("DEBUG")]
        static void CallMethod()
        {
            Console.WriteLine("I'm in! w00t!");
        }
    }

  2. public class Program
    {
        public static void Main(string[] args)
        {
            #if DEBUG
            CallMethod();
            #endif
        }

        #if DEBUG
        static void CallMethod()
        {
            Console.WriteLine("I'm in! w00t!");
        }
        #endif
    }

Advertisements

3 thoughts on “ConditionalAttribute

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