Attributes in C#.NET: which statements are correct about compilation, reflection, and parameters?
-
AOn compilation, attributes are removed from code and not recorded; reflection cannot read them
-
BAttributes are deleted at compile time, but reflection can still read them
-
CAttributes are recorded into assembly metadata; they can be read via reflection; attributes can take parameters
-
DAll of the listed statements are correct
-
ENone of the listed statements are correct
Answer
Correct Answer: Attributes are recorded into assembly metadata; they can be read via reflection; attributes can take parameters
Explanation
Introduction / Context:Attributes provide declarative metadata in .NET. Understanding their lifecycle—from source code to compiled assembly to runtime inspection—is important for using frameworks and tooling effectively.
Given Data / Assumptions:
- We consider what happens at compile time and how attributes are accessed at runtime.
- We consider whether attributes can have parameters (positional and named).
Concept / Approach:When a C# program is compiled, attributes are emitted as metadata in the resulting assembly (DLL/EXE). At runtime (and design-time), reflection APIs can read those attributes. Attributes support positional constructor arguments and named property/field assignments.
Step-by-Step Solution:
Compilation → attribute usages are preserved in metadata.Runtime → use reflection (MemberInfo.GetCustomAttributes) to query attributes.Parameters → attributes can accept constructor arguments and named arguments for public writeable properties/fields.Verification / Alternative check:Create a custom attribute with a constructor and a named property; apply it; then use reflection to retrieve and read both the positional and named values at runtime.
Why Other Options Are Wrong:Options asserting deletion or non-reflectability misunderstand the metadata model; attributes are not “thrown away.”
Common Pitfalls:Confusing attribute constructor parameters with named property initializers; forgetting that attributes are read-only at runtime in terms of behavior—they annotate, they don’t execute themselves.
Final Answer:Attributes are recorded into assembly metadata; they can be read via reflection; attributes can take parameters