Evil Code #004 : Conditional Attribute

Continuing with our series of subtle changes that make differences, let’s look into Conditional Attributes over Directives.

static void Main(string[] args)
{
Method01();
Method02();

Queue queue = new Queue();
queue.Enqueue("One");
queue.Enqueue("Two");
queue.Enqueue("Three");

Method03(queue.Dequeue());
Console.WriteLine(queue.Count);
Console.WriteLine("All Done");
Console.ReadLine();
}

// Approach One
private static void Method01()
{
#if DEBUG
Console.WriteLine("Hello Method01");
#endif
}
[Conditional("DEBUG")]
private static void Method02()
{
Console.WriteLine("Hello Method02");
}

[Conditional("DEBUG")]
private static void Method03(string Value)
{
Console.WriteLine(Value);
}

What would be the output of above code under
a) Debug Mode
b) Release Mode

The Debug Mode should be easy and as expected

Hello Method01
Hello Method02
One
2
All Done

What about release mode ?
3
All Done

You might have a tendency to say “2”, considering you might expect the dequeue statement to be executed. However, that is not the case. The dequeue is not called either because the result is not used as the method is not called.This leads to unexpected errors .
This is one the reasons why it is recommended not to decorate a method that accepts parameter with conditional Attributes.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s