Properties

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

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

C
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; 
                } 
        } 
    } 
}

D
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;
            }
        }
    }
}

ANS:B -

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

No answer description is available. Let's discuss.



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.