Search code examples
c#.netattributesconditional-attribute

Why can't I use ConditionalAttribute on a class?


I look into ConditionalAttribute declaration and it is declared like this:

I found JavaScript code that goes like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
   AllowMultiple = true)]
public sealed class ConditionalAttribute : Attribute {
  //whatever
}

and AttributeTargets.Class is claimed to mean that Attribute can be applied to a class. so I tried this:

[Conditional("DEBUG")]
class MyClass
{
}

but the compiler emits the following error

error CS1689: Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes

and MSDN says

This error only occurs with the ConditionalAttribute attribute. As the message states, this attribute can only be used on methods or attribute classes. For example, trying to apply this attribute to a class will generate this error.

So it looks like there's an attribute declared to be applicable to a class but trying to apply it to a class causes a compilation error.

How is this possible? Is that some hardwired special case or what?


Solution

  • Yes, ConditionalAttribute is a special case, being one of only a few attributes that are specifically handled directly by the compiler.

    The compiler would have no well-defined behaviour in that case, so it chooses not to let you do it, to avoid confusion.

    Of course, technically you could write a non-attribute class in MSIL that is marked with ConditionalAttribute, compile that with ilasm, and then reference it from a C# project - it would be interesting to know what the C# compiler does... I'm guessing it would do nothing special unless individual methods had the method too, since that is the scenario it targets.