C# Indexers
An indexer lets an object be used with square brackets, like an array. The class decides what each index reads and writes.
Setting and getting through an indexer
The Team class stores names in a private array. The indexer passes each access through to that array.
using System;
class Team
{
private string[] members = new string[3];
public string this[int index]
{
get { return members[index]; }
set { members[index] = value; }
}
}
class Program
{
static void Main(string[] args)
{
Team team = new Team();
team[0] = "Hana";
team[1] = "Bo";
Console.WriteLine(team[0]);
Console.WriteLine(team[1]);
}
}Overwriting and reading in a loop
Assignment through the indexer replaces a stored name. A loop then reads every slot by its index.
using System;
class Team
{
private string[] members = new string[3];
public string this[int index]
{
get { return members[index]; }
set { members[index] = value; }
}
}
class Program
{
static void Main(string[] args)
{
Team team = new Team();
team[0] = "Hana";
team[1] = "Bo";
team[2] = "Ana";
team[1] = "Cleo";
for (int i = 0; i < 3; i++)
{
Console.WriteLine(team[i]);
}
}
}An out-of-range read fails at run time
The array holds three slots, so index 5 does not exist. The read aborts the program with an exception.
using System;
class Team
{
private string[] members = new string[3];
public string this[int index]
{
get { return members[index]; }
set { members[index] = value; }
}
}
class Program
{
static void Main(string[] args)
{
Team team = new Team();
team[0] = "Hana";
Console.WriteLine(team[5]);
}
}Example
using System;
class Scores
{
private int[] values = new int[3];
public int this[int index]
{
get { return values[index]; }
set { values[index] = value; }
}
}
class Program
{
static void Main(string[] args)
{
Scores scores = new Scores();
scores[0] = 10;
scores[1] = 20;
scores[2] = 30;
int total = scores[0] + scores[1] + scores[2];
Console.WriteLine("Total: " + total);
}
}Key points
- An indexer is declared with this and the index type in brackets.
- The get part runs when a value is read through an index.
- The set part runs on assignment and receives the new value.
- The values usually live in a private array inside the class.
- Code outside the class uses the object name with brackets, such as team[0].
- An index outside the backing array throws an error at run time.
In this example, the Scores class wraps a private array of three ints. Each assignment runs the set part of the indexer and stores one score. The total line reads all three slots back through the get part. The sum prints as 60.
Note
An indexer has no name of its own, unlike a property.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What runs when the line `team[1] = "Bo";` executes?