Sunday, 3 February 2013

Conditional Attribute in C#

Conditional directives in C# are extremely useful to include or exclude regions of code from compilation. This allows you to target different platforms.

Consider a class Logger with a Log method. If you want to log a message only in debug mode you could do something like this.

This code is ugly isn't it?

This is an another way to do it but it is not exactly what we would like. The code works but there are lots of useless function calls that reduce the performance at run time.

This is the situation when the Conditional attribute is useful. The following code is equivalent to the first example but much more readable.

This attribute is in fact extensively used in the classes Debug and Trace.

The next time you use conditional directives, keep in mind the Conditional attribute.

No comments:

Post a Comment

What you think about this post? I really appreciate your constructive feedback (positive and negative) and I am looking forward to start a discussion with you on this topic.