C# - Implement Index Overloading

Here, we are going to learn how to implement index overloading using C# program?
Submitted by Nidhi, on November 09, 2020 [Last updated : March 22, 2023]

Here, we will overload the indexer of IndexOver class and then get and set the element of the array.

C# program to implement index overloading

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.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.