Search code examples
c#attributesconditional-compilation

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.


Solution

  • 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.