Home » C# Programming » Properties

Suppose a Student class has an indexed property. This property is used to set or retrieve values to/from an array of 5 integers called scores[]. We want the property to report "Invalid Index" message if the user attempts to exceed the bounds of the array. Which of the following is the correct way to implement this property?

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"); } } }

← Previous Question

More Questions from Properties

Discussion & Comments

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