1.

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?

A. <pre><code class="csharp">class Student { int[] scores = new int[5] {3, 2, 4,1, 5}; public int this[ int index ] { set { if (index &lt; 5) scores[index] = value; else Console.WriteLine("Invalid Index"); } } }</code></pre>
B. <pre><code class="csharp">class Student { int[] scores = new int[5] {3, 2, 4, 1, 5}; public int this[ int index ] { get { if (index &lt; 5) return scores[ index ]; else { Console.WriteLine("Invalid Index"); return 0; } } set { if (index &lt; 5) scores[ index ] = value; else Console.WriteLine("Invalid Index"); } } }</code></pre>
C. <pre><code class="csharp">class Student { int[] scores = new int[5] {3, 2, 4, 1, 5}; public int this[ int index ] { get { if (index &lt; 5) return scores[ index ]; else { Console.WriteLine("Invalid Index"); return 0; } } } }</code></pre>
D. <pre><code class="csharp">class Student { int[] scores = new int[5] {3, 2, 4, 1, 5}; public int this[ int index ] { get { if (index &lt; 5) scores[ index ] = value; else { Console.WriteLine("Invalid Index"); } } set { if (index &lt; 5) return scores[ index ]; else { Console.WriteLine("Invalid Index"); return 0; } } } }</code></pre>
Answer» C. <pre><code class="csharp">class Student { int[] scores = new int[5] {3, 2, 4, 1, 5}; public int this[ int index ] { get { if (index &lt; 5) return scores[ index ]; else { Console.WriteLine("Invalid Index"); return 0; } } } }</code></pre>


Discussion

No Comment Found

Related MCQs