C#.NET — Implementing a bounds-checked indexed property (indexer) for a 5-element scores array. Goal: The indexer should print "Invalid Index" when the user accesses beyond the last valid index.

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:

  • scores is an int[5]. Valid indices are 0..4.
  • Requirement: print "Invalid Index" when out of bounds.
  • We accept a simple check (index < 5); in production, include index >= 0 as well.


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:

Choose an indexer with both get and set accessors. In get: return scores[index] if valid; otherwise print a message and return a safe default (e.g., 0). In set: assign scores[index] if valid; otherwise print a message.


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:

  • A: Write-only; lacks a getter.
  • C: Read-only; lacks a setter.
  • D: Accessor bodies are swapped/incorrect and will not compile.
  • E: Incorrect because a correct implementation exists (option B).


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.

More Questions from Properties

Discussion & Comments

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