February 3

Conditional Attribute in C#

0  comments

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.


Tags


You may also like

The best way to stay up to date with C# 10 features

My Technical Journey from my first program to Lead Software Engineer

Top 10 C# Developer News from Microsoft Build 2020

Agile Estimation

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Subscribe to our newsletter now!

Get instant access to the Master C# 9 webinar to learn all the new exciting C# 9 features quickly.
Get regular videos and news on C# and .NET and offers on products and services to master C#.

We will collect, use and protect your data in accordance with our Privacy Policy.

>