Custom attributes in C#: which of the following cannot be a valid attribute target?

Difficulty: Easy

Correct Answer: Namespace

Explanation:


Introduction / Context:
Attributes annotate program elements to add metadata used by compilers, tools, and runtime frameworks. Not every syntactic element supports attribute application in C#.



Given Data / Assumptions:

  • Potential targets include: enum, event, delegate, interface, and namespace.
  • We are using C# attribute syntax with square brackets.


Concept / Approach:
In C#, attributes can target assemblies, modules, types (classes, structs, enums, interfaces, delegates), and members (methods, properties, events, fields), as well as parameters and return values. Namespaces are not valid attribute targets.



Step-by-Step Solution:

Enum → valid (e.g., [Flags]).Event → valid (attributes can decorate an event declaration).Delegate → valid (delegates are types).Interface → valid (interfaces are types).Namespace → invalid target in C#.


Verification / Alternative check:
Try applying an attribute directly to a namespace block; the compiler rejects it. Applying attributes to any of the other four compiles if AttributeUsage permits.



Why Other Options Are Wrong:
They list elements that are indeed valid attribute targets in C#.



Common Pitfalls:
Confusing assembly-level attributes with namespace annotations; only assemblies/modules accept those dedicated target specifiers.



Final Answer:
Namespace

Discussion & Comments

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