C# program to demonstrate the index overloading

Here, we are going to demonstrate the index overloading in C#.
Submitted by Nidhi, on November 09, 2020

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

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.