C#.NET — How can parameters be passed to attributes? Identify the valid approaches.

Difficulty: Easy

Correct Answer: 4, 5

Explanation:


Introduction / Context:
Attribute constructors accept positional (ctor) arguments and optional named arguments that set public read/write properties or fields of the attribute instance.



Given Data / Assumptions:

  • We are talking about attribute parameter passing forms in C#.
  • Attributes are instantiated by the compiler in metadata; user code does not pass references/addresses at run-time.


Concept / Approach:
Two valid forms exist: positional arguments (via constructor) and named arguments (via property/field assignment syntax). There is no “by ref” or “by address” parameter passing for attributes.



Step-by-Step Solution:

Positional: [MyAttr(10, "x")] calls a constructor MyAttr(int, string).Named: [MyAttr(10, Name = "x", Enabled = true)] sets writable members.Ref/out/address passing is not supported in attribute specifications.


Verification / Alternative check:
Try compiling examples using named and positional arguments; attempts to use ref/out will fail to compile.



Why Other Options Are Wrong:
“By reference” and “by address” are not part of attribute argument syntax.



Common Pitfalls:
Expecting arbitrary expressions or ref/out parameters in attribute arguments; attribute arguments must be compile-time constants or typeof/nameof where allowed.



Final Answer:
4, 5

Discussion & Comments

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