C#.NET indexers — A Student class exposes an indexed property over an int[5]. Which usages are correct?

Difficulty: Easy

Correct Answer: 2) Student s = new Student(); s[3] = 34;

Explanation:


Introduction / Context:
Indexers in C#.NET let an object behave like an array using the syntax obj[index]. They are instance members; C# does not support static indexers. This problem asks which example statements correctly use such an indexed property of a Student class that maps to a 5-element integer array.



Given Data / Assumptions:

  • Student defines an instance indexer taking one int parameter.
  • We want valid C# syntax and semantics.
  • Console.WriteLine can read from the indexer if a get accessor exists.


Concept / Approach:
Valid usage requires a Student instance (constructed with new) and then either assignment via the set accessor or reading via the get accessor. Static-like forms such as Student[3] are invalid. Also, constructs like Student.this are not C# syntax and should be rejected.



Step-by-Step Solution:

Statement 2: Create s; assign s[3] = 34 → valid (requires set accessor).Statement 3: Create s; read Console.WriteLine(s[3]) → valid if indexer has get.Statement 1: Student[3] = 34 → invalid (no static indexers).Statement 4: Console.WriteLine(Student[3]) → invalid for same reason.Statement 5: Student.this ... → invalid syntax in C#.


Verification / Alternative check:
Declare public int this[int i] { get; set; } inside Student, then compile and test statements 2 and 3 successfully.



Why Other Options Are Wrong:

  • 1 and 4: Attempt static indexer access → illegal in C#.
  • 5: Nonsensical C# syntax.


Common Pitfalls:
Forgetting that indexers are instance-based; also mixing up property indexers with arrays declared at the type level.



Final Answer:
2, 3

More Questions from Properties

Discussion & Comments

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