Custom attribute targets in C#: how do you specify what elements an attribute can be applied to?

Difficulty: Easy

Correct Answer: By applying AttributeUsage to the custom attribute class definition

Explanation:


Introduction / Context:
When you create a custom attribute in C#, you typically want to control where it can be used (e.g., on classes, methods, properties). This is done with AttributeUsage.



Given Data / Assumptions:

  • The attribute class derives from System.Attribute.
  • We need to set allowed targets and other options (AllowMultiple, Inherited).


Concept / Approach:
Apply [AttributeUsage(...)] or its full name [AttributeUsageAttribute(...)] to the attribute class definition. Both forms are equivalent because of the C# attribute naming convention that allows omitting the trailing “Attribute”.



Step-by-Step Solution:

Use [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] above the attribute class.This precisely controls valid targets and behavior.UsageAttribute does not exist; the automatic “applies to all targets” behavior is false.


Verification / Alternative check:
Attempt to apply the attribute to a disallowed target; the compiler will emit an error referencing AttributeUsage settings.



Why Other Options Are Wrong:
“UsageAttribute” is not a framework attribute. Attributes do not default to “all targets.”



Common Pitfalls:
Forgetting that AttributeUsage controls inheritance and multiplicity; omitting it leads to default values (AttributeTargets.All, AllowMultiple = false, Inherited = true for some cases), which might not match your intent.



Final Answer:
By applying AttributeUsage to the custom attribute class definition

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion