C# Program to Implement use of Indexers
Posted by Superadmin on August 15 2022 14:11:23

C# Program to Implement use of Indexers

 

 

 

This is a C# Program to implement use of indexers.

Problem Description

This C# Program Implements Use of Indexers.

Problem Solution

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

Program/Source Code

Here is source code of the C# Program to Implement Use of Indexers. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Implement Use of Indexers
 */
class values
{
    private int[] val = new int[10] { 10,20,30,40,50,60,70,80,90,100 }; 
    public int Length
    {
        get { return val.Length; }
    } 
    public int this[int index]
    {
        get
        {
            return val[index];
        }
 
        set
        {
            val[index] = value;
        }
    }
}
class MainClass
{
    static void Main()
    {
        values newval = new values();
        newval[3] = 58;
        newval[5] = 60;
        for (int i = 0; i < 10; i++)
        {
            System.Console.WriteLine("Element #{0} = {1}", i, newval[i]);
        }
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
 
    }
}
Program Explanation

This C# program is used to implement the use of indexers. Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

 
Runtime Test Cases
 
Element #0 : 10
Element #1 : 20
Element #2 : 30
Element #3 : 58
Element #4 : 50
Element #5 : 60
Element #6 : 70
Element #7 : 80
Element #8 : 90
Element #9 : 100
Press any key to exit