Q:

C# program to implement indexer for an integer array

belongs to collection: C# Basic Programs | array programs

0

C# program to implement indexer for an integer array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | array programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to convert negative values an integer a... >>
<< C# program to search an item in an array using bin...