Using Indexers in C#

Indexers are elements in a C# program that allow a Class to behave as an Array. You would be able to use the entire class as an array. In this array you can store any type of variables. The variables are stored at a separate location but addressed by the class name itself. Creating indexers for Integers, Strings, Boolean etc. would be a feasible idea. These indexers would effectively act on objects of the class.

Lets suppose you have created a class indexer that stores the roll number of a student in a class. Further, lets suppose that you have created an object of this class named obj1. When you say obj1[0], you are referring to the first student on roll. Likewise obj1[1] refers to the 2nd student on roll. 

Therefore the object takes indexed values to refer to the Integer variable that is privately or publicly stored in the class. Suppose you did not have this facility then you would probably refer in this way: 
  • obj1.RollNumberVariable[0]
  • obj1.RollNumberVariable[1]. 
 where RollNumberVariable would be the Integer variable.

Now that you have learnt how to index your class & learnt to skip using variable names again and again, you can effectively skip the variable name RollNumberVariable by indexing the same.

Indexers are created by declaring their access specifier and WITHOUT a return type. The type of variable that is stored in the Indexer is specified in the parameter type following the name of the Indexer. Below is the program that shows how to declare and use Indexers in a C# Console environment:



using System;

namespace Indexers_Example
{
    class Indexers
    {
        private Int16[] RollNumberVariable;

        public Indexers(Int16 size)
        {
            RollNumberVariable = new Int16[size];

            for (int i = 0; i < size; i++)
            {
                RollNumberVariable[i] = 0;
            }
        }

        public Int16 this[int pos]
        {
            get
            {
                return RollNumberVariable[pos];
            }
            set
            {
                RollNumberVariable[pos] = value;
            }
        }
    }
}

using System;

namespace Indexers_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Int16 size = 5;

            Indexers obj1 = new Indexers(size);

            for (int i = 0; i < size; i++)
            {
                obj1[i] = (short)i;
            }

            Console.WriteLine("\nIndexer Output\n");

            for (int i = 0; i < size; i++)
            {
                Console.WriteLine("Next Roll No: " + obj1[i]);
            }

            Console.Read();
        }
    }
}

Indexers can be overloaded as well. Give it a try!

Indexers are different from Properties in the following ways:



Custom Search