Q:

C# program to demonstrate the index overloading

0

C# program to demonstrate the index overloading

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to demonstrate the indexer overloading is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate indexer overloading.

using System;

class IndexOver
{
    int [] arr = new int[3];

    public int this[int index]
    {
        get
        {
            return arr[index];
        }

        set
        {
            arr[index] = value;
        }
    }


    public int this[float index]
    {

        get
        {
            return arr[2];
        }

        set
        {
            arr[2] = value;
        }
    } 

    static void Main(string[] args)
    {
        IndexOver Ob = new IndexOver();

        Ob[0] = 10;
        Ob[1] = 20;

        //Float indexer called
        Ob[1.2F] = 30;

        Console.WriteLine("Ob[0]     :" + Ob[0]     );
        Console.WriteLine("Ob[1]     :" + Ob[1]     );
        Console.WriteLine("Ob[1.2F]  :" + Ob[1.2F]  );
    }
}

Output:

Ob[0]     :10
Ob[1]     :20
Ob[1.2F]  :30
Press any key to continue . . .

Explanation:

In the above program, we created a class IndexOver that contains an array arr as a data member. Then we overloaded the indexer based on the index. Here, we used to float and int index to overload indexer.

Now look to the Main() method. Here we created the object Ob and then set and get the elements of the array using an overloaded indexer.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to demonstrate the concept of method hi... >>
<< C# program to demonstrate the constructor overload...