Indexers in C#

Posted by

Indexers in C#

Indexers in csharp

Image Credit:

Indexers in C# can be used to access a class or struct by means of array. Well this is a strange aspect but we can traverse through the objects such as classes or structs through the indexers. Let’s see an example that demonstrates this

using System;

class Jungle
private string[] animals = new string[3];

public string this[int index]
return animals[index];
animals[index] = value;

class Program
public static void Main()
Jungle animals = new Jungle();
animals[0] = “Tiger”;
animals[1] = “Zebra”;
animals[2] = “Elephant”;

for (int i = 0; i < 3; i++) Console.WriteLine(animals[i]); Console.ReadLine(); } }



An indexer can be visualized as a property with parameter. We generally apply some logic on the value of the parameter such as if condition, coalesce operator ?? etc.

The differences between an indexer and a property are shown in the following chart


Let’s say you have a collection of objects that you want to be able to index by something other than the order in which it was placed in a collection. In the example below, you can see how you could use the ‘Location’ property of some object and using the indexer, return all objects in the collection that match you location, or in the second example, all objects that contain a certain Count() of objects.

class MyCollection {

public IEnumerable this[string indexer] {
get{ return this.Where(p => p.Location == indexer); }

public IEnumerable this[int size] {
get{ return this.Where(p => p.Count() == size);}


In order to see the practical practice of Indexers in C#; See my uploaded slides:

Facebook Comments

Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.
Syed Adeel Ahmed on FacebookSyed Adeel Ahmed on GoogleSyed Adeel Ahmed on InstagramSyed Adeel Ahmed on Twitter