C#.NET — AttributeUsage targeting: can a custom attribute be restricted to specific elements only?

Difficulty: Easy

Correct Answer: Classes, Methods and Member-Variables

Explanation:


Introduction / Context:
When you create a custom attribute, you can restrict where it may be applied using the AttributeUsage attribute (AttributeTargets flags).



Given Data / Assumptions:

  • We want to scope an attribute to certain program elements.
  • Typical targets include Class, Method, Property, Field, Parameter, ReturnValue, etc.


Concept / Approach:
Apply [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Field)] to limit where the custom attribute may appear. Thus it can be applied to classes, methods, and member variables (fields) if configured.



Step-by-Step Solution:

Define the attribute class deriving from System.Attribute.Annotate it with AttributeUsage specifying the allowed targets.Attempting to use the attribute elsewhere will produce a compile-time error.


Verification / Alternative check:
Try applying to a disallowed target and observe the compiler’s diagnostic.



Why Other Options Are Wrong:
Options that mention only a subset are possible but the question asks whether it is possible to target multiple specific elements (including fields), which is true.



Common Pitfalls:
Forgetting that AttributeTargets is a flags enum and can be combined with bitwise OR.



Final Answer:
Classes, Methods and Member-Variables

More Questions from Attributes

Discussion & Comments

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