Working with indexers in C#

Working with indexers in C#

Introduction

An Indexer allows you to access a class as an array. The index values can be set or retrieved without explicitly specifying a type or instance member of the class.

The indexer is similar to properties but the accessors of indexers do not accept parameters. An indexer can be overloaded like functions.

Creating an Indexer

Indexers are created using this keyword. In the example shown below, I have created an Employee class with an indexer to store the names of employees.

In visual studio you can easily insert and indexer snippet by typing indexer and pressing the tab key twice.

namespace CSConsole
{
     class Employees
     {
         string[] Emp = new string[10];
         public string this[int index]
         {
             get { return Emp[index]; }
             set { Emp[index] = value; }
         }
     }
     class Program
     {
         static void Main(string[] args)
         {
             Employees e = new Employees();
             e[0] = "John Doe";
             e[1] = "Jane Doe";
             Console.WriteLine("Employees {0}, {1}", e[0], e[1]);
             Console.ReadKey();
         }
     }
}

Output

Employees John Doe, Jane Doe

You might have noticed that the object e of the class Employees is directly used as an array to store the names of Employees. I have not specified the name of the member (array) Emp in which the names actually the names are stored. It is made possible using Indexers. The indexer automatically stores the data in its member that matches the pattern.

Digging a little deeper

In some cases, we may need to perform some actions before storing or accessing the data.

For example, we have not implemented any safety checks in our code. The array Emp, that holds the names of employees, can hold only a maximum of ten members in our example. Guess what will happen if I try to add or retrieve the 11th element.

In such cases, we can write our code to be executed before setting or retrieving data.

class Employees
{
    string[] Emp = new string[10];
    public string this[int index]
    {
        get {
            if(index <0 || index>=Emp.Count())
            {
                 throw new IndexOutOfRangeException("Index must be between 0 and 10");
            }
            else
            {
                 return Emp[index];
             }
         }
         set {
             if (index < 0 || index >= Emp.Count())
             {
                 throw new IndexOutOfRangeException("Index must be between 0 and 10");
             }
             else
             {
                 Emp[index] = value;
             }
         }
     }
}

Points to remember

  • An indexer allows you to use a class as an array.
  • You do not need to specify the name of the member to set or retrieve data.
  • Indexers are created using this keyword.
  • Indexers can be overloaded.
  • The accessor of an indexer does not accept parameters.
0 Comments
Loading...