Difficulty: Easy
Correct Answer: class Student { int[] scores = new int[5] {3, 2, 4, 1, 5}; public int this[int index] { get { if (index < 5) return scores[index]; else { Console.WriteLine("Invalid Index"); return 0; } } set { if (index < 5) scores[index] = value; else Console.WriteLine("Invalid Index"); } } }
Explanation:
Introduction / Context:
Indexers in C#.NET allow array-like access to class or struct instances. Here, the Student indexer should both read and write scores while warning when the index exceeds the allowed range.
Given Data / Assumptions:
Concept / Approach:
A well-formed indexer includes both get and set accessors when read-write access is needed. Each accessor should validate the index and either proceed or report an error state.
Step-by-Step Solution:
Verification / Alternative check:
Testing with index = 4 works; index = 5 prints "Invalid Index". Adding index < 0 checks further hardens the code.
Why Other Options Are Wrong:
Common Pitfalls:
Forgetting the lower-bound check or mixing up get/set logic bodies.
Final Answer:
Option B (read-write indexer with bounds check) is correct.
Discussion & Comments