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.

Permanent link to this article:

Warning: in_array() expects parameter 2 to be array, null given in /home/andreaa9/public_html/wp-content/themes/graphene/inc/plugins.php on line 92