How does inheritance of attribute classes work in C#? To clarify, I am talking about the inheritance of the attribute classes themselves (i.e. base classes of System.Attributes
), NOT any classes that happen to have them as attribute.
For some reason, I cannot seem to find anything on this (my searches always turn up with the other meaning).
For example, if a have a class AttributeA
which extends System.Attribute
:
Do I have to separately mark subclasses of AttributeA
with [AttributeUsage()]
. (Since System.AttributeUsage
's inheritance is true
, I don't think I will.)
Will AllowMultiple=false
on the AttributeUsage
of AttributeA
prevent me from having multiple subclasses of AttributeA
for attributes?
EDIT:
Programmers can only read code.
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false)]
class AttributeA
{ }
class AttributeB : AttributeA
{ }
class AttributeC : AttributeA
{ }
[AttributeB]
[AttributeC]
class Foo
{ }
Does this work?
(I was finally able to try it.)
The example code does compile. I still like to have documentation, although I suppose C# is C# and it isn't going to change that. (Right?)
Evidently:
AttributeUsage
, as expected.AllowMultiple
refers only to attributes of (strictly) the original class, not subclasses.AttributeUsage
can be effectively "re-defined". With
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
class AttributeA : Attribute
{ }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
class AttributeB : AttributeA
{ }
class AttributeC : AttributeA
{ }
the following is okay
[AttributeA]
[AttributeB]
[AttributeB]
[AttributeC]
class Foo
{ }
but this isn't
[AttributeA]
[AttributeB]
[AttributeC]
[AttributeC]
class Foo
{ }
You can control this behavior by using the named parameter Inherited for your AttributeUsageAttribute.
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
class AttributeA
{ }
class AttributeB : AttributeA
{ }
class AttributeC : AttributeA
{ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With