Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 529
sharptooth Avatar asked Dec 25 '22 13:12

sharptooth


2 Answers

Okay:

[Conditional("DEBUG")]
public void foo() { }

Okay too:

[Conditional("DEBUG")]
public class BarAttribute : Attribute { }

Not okay:

[Conditional("DEBUG")]
public class Baz { }

ConditionalAttribute can be applied to classes, but there's an additional restriction of the class being an attribute class.

If you want the whole class to be removed based on conditional define, then no, you can't to it. It's not supported. You'll have to mark each method individually.

like image 57
Athari Avatar answered Jan 06 '23 05:01

Athari


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.

like image 42
Marc Gravell Avatar answered Jan 06 '23 04:01

Marc Gravell