C# Indexers

Updated on     Kisan Patel

Indexers can be termed as location indicators and they are used to access class objects in the same way as array elements are accessed.

Note : Implementing indexers is similar to implementing properties using the get and set functions. The only difference is that call an indexer, you pass an indexing parameter.

You can define indexer by using the this keyword, which refers to the object instance.

The syntax for declaring an indexer:

<access modifier> <Return Type> this[argument list]
{
	get
	{ //code for get }
	set
	{ //code for set }
}

Let’s take one example to understand how indexers in C# works.

using System;

namespace ConsoleApp
{
    class List
    {
        string[] namelist = new string[3];
        public string this[int index]
        {
            get
            {
                if (index < 0 || index >= namelist.Length)
                {
                    throw new Exception("Index out of range.");
                }
                else
                {
                    return (namelist[index]);
                }
            }
            set
            {
                namelist[index] = value;
            }
        }
    }

    class Tester
    {
        public static void Main(string[] args)
        {
            List list = new List();
            list[0] = "Kisan";
            list[1] = "Devang";
            list[2] = "Ravi";
            for (int i = 0; i <= 2; i++)
                Console.WriteLine(list[i]);
        }
    }
}

Here is the output of the above C# program…

c-sharp-indexers-example

This program includes a List class with an indexer we define. The Layout class contains an indexer that has get and set method bodies. These accessors have logic that ensures the array will not will be accessed out-of-bounds.

Note : C# indexers must have at least one parameter; otherwise, the compiler gives an error.

C#

Leave a Reply