C# program to implement indexer for an integer array

Here, we are going to learn how to implement indexer for an integer array in C#?
Submitted by Nidhi, on August 22, 2020

Here we will create an indexer to set and get elements of an integer array.

Program:

The source code to implement an indexer for an integer array in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to implement indexer for 
//an integer array in C#

using System;

class intValues
{
    private int[] intArray = { 90,89,88,87,86,85,84,83,82,81 }; 
    public int Size
    {
        get 
        { 
            return intArray.Length; 
        }
    } 
    public int this[int index]
    {
        get
        {
            return intArray[index];
        }
 
        set
        {
            intArray[index] = value;
        }
    }
}

class Demo
{
    static void Main()
    {
        intValues vals = new intValues();
        int loop = 0;
        
        vals[2] = 47;
        vals[4] = 67;
        vals[6] = 74;

        for (loop = 0; loop < vals.Size; loop++)
        {
            Console.Write(vals[loop]+" ");
        }
        Console.WriteLine();
    }
}

Output:

90 89 47 87 67 85 74 83 82 81
Press any key to continue . . .

Explanation:

In the above program, we created class intValues that contains integer array, here we implement indexer using "this" to get and set the items into an array.

We also created one more class Demo that contains the Main() method. Here we created object vals of intValues class then we assigned values 47, 67, and 74 on 2, 4, 6 indexes respectively. Then we print elements of the array using the "foreach" loop.






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.