Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Or operator in Conditional attribute in C#

Tags:

c#

In C# we can differentiate code execution depending on the type of build. By default we have Debug and Release types defined.
We can do it using the #if directive:

#if DEBUG     public void Foo()     { ... } #endif 

But we can also use Conditional attribute:

[Conditional("DEBUG")] public void Foo() { ... } 

The second solution is even claimed to be more maintainable (see: Effective C# by Bill Wagner).

My question is - how can I use the Conditional attribute with many build configurations? Is it possible to somehow use the or operator? I ask because I want some Foo method to be executed both in, for example, the DEBUG and BAR build configurations. What then?

like image 309
Arkadiusz Kałkus Avatar asked Dec 02 '15 08:12

Arkadiusz Kałkus


People also ask

What is conditional attributes?

A conditional attribute is a tag used to mark a method or class whose execution depends on the definition of preprocessing identifier. A conditional attribute indicates a condition to specify conditional compilation wherein methods are selectively called on the basis of definition of symbols.

What is an attribute C#?

Advertisements. An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute.


1 Answers

You can use multiple comma separated conditional attributes like

[Conditional("DEBUG"), Conditional("BAR")] 

and it will be exactly your desired behaviour - they will be logically ORed together.

See MSDN for reference.

like image 63
Andrey Korneyev Avatar answered Sep 22 '22 03:09

Andrey Korneyev