Indexer kavramı C# dilinde tipleri diziler gibi kullanılabilir hale getirmektedir. Tiplere ait nesneler tıpkı bir diziymiş gibi indexlere sahiptirler. Bunu örneklerle incelemeye çalışalım.
Tek boyutlu indexer
class Week
{
string[] week = new string[]{"Pazartesi","Salı","Çarşamba","Perşembe","Cuma","Cumartesi","Pazar"};
public string this[int i]
{
get { return i >= 0 && i < 7 ? this.week[i] : "Hatalı İndex"; }
}
}
Haftanın günlerini temsil eden Week sınıfımızı oluşturduk. Week sınıfından oluşturulan nesneler üzerinden sınıf içindeki dizi elemanlarına Indexer sayesinde erişebilecek duruma geldik.
static void Main(string[] args)
{
Week days = new Week();
for (int i = -1; i < 8; i++)
{
Console.WriteLine(days[i]);
}
}
Sonuç:
İki Boyutlu Indexer
class Coordinates
{
int[,] coordinates = new int[,] { { 10, 12 }, { 58, 46 }, { 16, 76 } };
public int this[int i, int j]
{
get { return coordinates[i, j]; }
}
}
static void Main(string[] args)
{
Coordinates coor = new Coordinates();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine(coor[i,j]);
}
}
}
Sonuç:

