Indexers in C#




Indexers in C#

Indexers in csharp

Image Credit: http://1.bp.blogspot.com

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]
{
get
{
return animals[index];
}
set
{
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(); } }

Output

Tiger
Zebra
Elephant

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

image credit:msdn.com

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);}
}
}

reference:http://stackoverflow.com/questions/2185071/real-world-use-cases-for-c-sharp-indexers

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


Syed Adeel Ahmed
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.

Published by

Syed Adeel Ahmed

Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.