C# - 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 [Last updated : August 26, 2023]

C# Indexer

In C# programming language, a C# indexer is commonly known as a smart array. It is a class property that can be used to access the class or struct members using the features of an array. C# "this" keyword is used to create an indexer in C#. It can be applied to both class and structure.

Problem statement

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

C# program to implement indexer for an integer array

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.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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