Indexers
Access objects with array-like syntax.
What Is an Indexer?
An indexer lets an object be accessed with [ ] syntax, like an array. You define it with this[...]. It is perfect for collection-like classes.
using System;
class Week
{
private string[] _days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
public string this[int index] => _days[index];
}
class Program
{
static void Main()
{
var w = new Week();
Console.WriteLine(w[0]);
Console.WriteLine(w[6]);
}
}Indexer Syntax
An indexer looks like a property but uses this and takes a parameter list in brackets. It has get and optionally set.
using System;
class Scores
{
private int[] _data = new int[5];
public int this[int i]
{
get { return _data[i]; }
set { _data[i] = value; }
}
}
class Program
{
static void Main()
{
var s = new Scores();
s[0] = 90;
s[1] = 75;
Console.WriteLine(s[0] + ", " + s[1]);
}
}