C#.NET — Attributes: identify the correct statement about custom attributes and runtime behavior.

C# Programming Attributes Difficulty: Easy
Choose an option
  • A
    If the custom attribute class is named BugFixAttribute, the compiler searches only for BugFix in usage sites.
  • B
    To create a custom attribute we must create a struct and derive it from System.Attribute.
  • C
    To create a custom attribute we must implement IAttribute in a class.
  • D
    If BugFixAttribute takes three parameters, it must also have a zero-argument constructor.
  • E
    The CLR can alter behavior based on the attributes applied to code.

Answer

Correct Answer: The CLR can alter behavior based on the attributes applied to code.

Explanation

Introduction / Context:Attributes are classes that carry metadata and, in many scenarios, drive runtime or framework behavior (serialization, remoting, interop, security, binding, etc.). This question distinguishes true facts from common misconceptions.

Given Data / Assumptions:

  • Custom attribute naming convention: “XAttribute” class can be used via [X] or [XAttribute].
  • Attributes are reference types deriving from System.Attribute.
  • Constructors define required positional parameters; zero-argument constructors are optional.

Concept / Approach:Only classes (not structs) derive from System.Attribute to create custom attributes. There is no IAttribute interface to implement. The runtime and frameworks often read attributes to change behavior (e.g., [Serializable], [NonSerialized], [DllImport], [Obsolete] affects compilation).

Step-by-Step Solution:

Option A: Incorrect. With a class BugFixAttribute, usage can be [BugFix] or [BugFixAttribute]; the compiler recognizes the “Attribute” suffix.Option B: Incorrect. Attributes must be classes, not structs.Option C: Incorrect. There is no required IAttribute interface.Option D: Incorrect. Only constructors actually declared are required; no mandatory parameterless constructor.Option E: Correct. Many attributes influence runtime or framework behavior.

Verification / Alternative check:Declare a custom attribute deriving from System.Attribute and observe reflection and framework behaviors.

Why Other Options Are Wrong:They contradict the attribute class model and naming conventions.

Common Pitfalls:Assuming an interface-based attribute model or that parameterless constructors are mandated.

Final Answer:The CLR can alter behavior based on the attributes applied to code.

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