A simple indexer example in C#

Indexers enables us to create a class, struct, or interface that applications can access just as an array. Indexers resemble properties except that their accessors take parameters. In the following example we have a class named CountiresIndexers in the ConsoleApplication2 project that represents the name of the countries. The class contains an array named “CountryData” of string type to store the countriy’s names.
To declare an indexer on a class, we are using the this keyword, as in this example:
 

using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleApplication2
{
    using System;
 
    /// <summary>
    ///     A simple indexer example.
    /// </summary>
    class CountiresIndexers
    {
        private string[] CountryData;
 
        public CountiresIndexers(int size)
        {
            CountryData = new string[size];
 
            for (int i = 0; i < size; i++)
            {
                CountryData[i] = "empty";
            }
        }
 
        public string this[int pos]
        {
            get
            {
                return CountryData[pos];
            }
            set
            {
                CountryData[pos] = value;
            }
        }
 
        static void Main(string[] args)
        {
            int size = 10;
            CountiresIndexers conInd = new CountiresIndexers(size);
            conInd[9] = "India";
            conInd[3] = "Japan";
            conInd[5] = "USA";
            conInd[2] = "Germany";
            conInd[1] = "France";
 
            Console.WriteLine("Output\n");
 
            for (int i = 0; i < size; i++)
            {
                Console.WriteLine("conInd[{0}]: {1}", i, conInd[i]);
            }
 
            System.Console.WriteLine("\n\n");
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

 
By implementing an indexer in this class. We can set the country name directly to class instance as :
conInd[2] = “Germany”; And you can direct access to the instance CountryData[i] also.
I hope the above is the simple example helps to understand the concept of Indexer.

Author: Hirendra Sisodiya

Programmer at PSPL. Can be found on Google Plus.