C#.NET indexers — Student must support two-dimensional indexing as in: Student s = new Student(); s[1, 2] = 35; Which declaration enables this write-only indexer?

Difficulty: Medium

Correct Answer: class Student\n{\n int[,] a = new int[5, 5];\n public int this[int i, int j]\n { set { a[i, j] = value; } }\n}

Explanation:


Introduction / Context:
C# indexers can accept multiple parameters, enabling two-dimensional indexing syntax like s[i, j]. To make only assignments possible (write-only), the indexer should expose only a set accessor and omit a get accessor.



Given Data / Assumptions:

  • Student uses an internal 2D int array (int[,]) for storage.
  • Goal: support s[1, 2] = 35; (write-only indexer).
  • We use correct C# keywords and syntax.


Concept / Approach:
A valid two-parameter indexer has the form public int this[int i, int j] { set { a[i, j] = value; } }. The indexer’s declared type (int) is the value being assigned. No get accessor means reads like var x = s[1,2]; are disallowed.



Step-by-Step Solution:

Choose int[,] backing array for true 2D storage.Declare public int this[int i, int j] with only set.Inside set, assign value into a[i, j].Avoid invalid keywords like property or WriteOnly (VB terms).


Verification / Alternative check:
Compile the declaration and test with the given assignment; it compiles. Attempting to read s[1,2] will fail, as intended.



Why Other Options Are Wrong:

  • A/B: Use VB-style keywords and, in A, the backing array type is wrong (int[] with 2D size).
  • D: Invalid indexer signature; missing parameters in the indexer declaration.


Common Pitfalls:
Confusing jagged arrays with rectangular arrays and mixing language keywords from VB into C#.



Final Answer:
class Student { int[,] a = new int[5, 5]; public int this[int i, int j] { set { a[i, j] = value; } } }

Discussion & Comments

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