C# Programming - Properties - Discussion

Discussion Forum : Properties - General Questions (Q.No. 13)
13.
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?
class Student
{
    int[] scores = new int[5] {3, 2, 4,1, 5}; 
    public int this[ int index ]
    { 
        set
        { 
            if (index < 5)
                scores[index] = value; 
            else
                Console.WriteLine("Invalid Index");
        } 
    } 
}
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"); 
        } 
    } 
}
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; 
                } 
        } 
    } 
}
class Student
{
    int[] scores = new int[5] {3, 2, 4, 1, 5}; 
    public int this[ int index ]
    { 
        get
        {
            if (index < 5)
                scores[ index ] = value; 
            else
            { 
                Console.WriteLine("Invalid Index");
            } 
        }
        set
        { 
            if (index < 5)
                return scores[ index ];
            else
            { 
                Console.WriteLine("Invalid Index");
                return 0;
            }
        }
    }
}
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.