Jarrett Robertson
Jarrett Robertson

Reputation: 459

Is there a way to mark an attribute as conditional

So, I was working with some attributes and then I realized it might be helpful for me to have an attribute that is conditional on whether or not I build in debug or release.

It turns out I couldn't find what I was looking for by searching google or stack overflow. There is an attribute called [Conditional] and there is a [DebuggerDisplay] but I couldn't find one that set an attribute itself as conditional.

The following link explains the [Conditional] vs #if Debug #if DEBUG vs. Conditional("DEBUG")

What I'm looking for is closer to only preferably in attribute form.

#if DEBUG
    [SomeAttribute(...)]
#endif

I realize I can do a #define and then use the correct symbol which would stop me from having to #if debug all over, but I feel like there should be an attribute flag that I don't know about.

Upvotes: 4

Views: 2194

Answers (2)

Parimal Raj
Parimal Raj

Reputation: 20565

No, I don not think so.

If you want to include code that is compiled conditionally you have to use these #if, #else, #elif #endif compiler directives, there is no absolute way to do it without it.

You can even use the ConditionalAttribute on ur Attribute class, but it gets compiled into the assembly, but later gets optimized by the JIT compiler.


This should help you understand : How does the Conditional attribute work? and Omitting code: Any difference between Conditional Attribute and pre-processing directive?

Upvotes: 1

vcsjones
vcsjones

Reputation: 141588

This depends a little bit on exactly what you are trying to achieve.

If you are the author of SomeAttribute, and you want all applications of that attribute to be conditional, then you can apply the Conditional attribute on the type declaration itself:

[Conditional("DEBUG")]
[System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class SomeAttribute : Attribute
{
    ...

If you do not have the source for SomeAttribute, or you do not want it to be all-or-nothing, then preprocessor statements are all that is left as far as what is built-in.

Upvotes: 5

Related Questions