logo codesdope

Indexer in C#


Indexers are like properties which are generally used to set and get data from an array field of a class. Indexer allows us to use [] operator directly on the object of a class to access the array field inside the class. For example, if obj is an object of any class and that class also has a field names which is an array of strings, we can access the elements of the array field names directly with the object like obj[0], obj[1], etc.

Unlike properties, indexers use this keyword instead of any name and also take a parameter - Modifier returnType this[parameters]. It is similar to a property, we have just used this instead of a name and it is also taking parameters.

Let's take an example.

using System;

class Student
{
  private string[] names = new string[5];

  public string this[int index]
  {
    get
    {
      return this.names[index];
    }
    set
    {
      this.names[index] = value;
    }
  }
}

class Test
{
  static void Main(string[] args)
  {
    Student batch1 = new Student();

    batch1[0] = "abc";
    batch1[1] = "xyz";

    Console.WriteLine(batch1[0]);
    Console.WriteLine(batch1[1]);
  }
}
Output
abc
xyz

In this example, the indexer is taking an integer as its parameter which is index. We are using this index to set the elements of the array names in set accessor and we are also returning the elements in get accessor. To access the elements of the array names, we have directly used [] operator on the object - batch1[0] and batch1[1].

Indexer Overloading


We can also overload an indexer with different parameters. Let's take an example.

using System;

class Student
{
  private string[] names = new string[5];

  public string this[int index]
  {
    get
    {
      return this.names[index];
    }
    set
    {
      this.names[index] = value;
    }
  }

  public string this[string s]
  {
    get
    {
      return "Overloading";
    }
  }
}

class Test
{
  static void Main(string[] args)
  {
    Student batch1 = new Student();

    batch1[0] = "abc";
    batch1[1] = "xyz";

    Console.WriteLine(batch1[0]);
    Console.WriteLine(batch1["abc"]);
  }
}
Output
abc
Overloading

In this example, we have overloaded an indexer with an integer argument with a string argument.


Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.