below is the source code of AttributeUsageAttribute
:
[Serializable] [AttributeUsage(AttributeTargets.Class, Inherited = true)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AttributeUsageAttribute : Attribute { internal AttributeTargets m_attributeTarget = AttributeTargets.All; // Defaults to all internal bool m_allowMultiple = false; // Defaults to false internal bool m_inherited = true; // Defaults to true internal static AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All); //Constructors public AttributeUsageAttribute(AttributeTargets validOn); internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited); //Properties ... }
I have two questions:
Q1-Why can you apply a just-defined attribute on itself? isn’t it going to cause infinite loop/stackoverflow?
Q2-The attribute on top of the AttributeUsageAttribute indicates that AttributeUsageAttribute
can only be applied to class targets.
But inside the attribute class, it is default to be used for all targets such as assembly, module, class, method…Aren’t they contradicting to each other?
Answer
isn’t it going to cause infinite loop/stackoverflow?”
Why should it? it’s not like the class gets redeclared every time it’s used. The class is declared once, and the attribute is applied once. I don’t see any opportunity for recursion here.
“Aren’t they contradicting to each other?”
Where’s the contradiction? This attribute is used to modify other attributes. It’s fine for this attribute to apply only to classes, even as it can be used to dictate whether some other attribute (which is necessarily a class) can be applied only to a class, assembly, module, etc.