Glossary / Indexers
Indexers
An indexer lets an instance be accessed with bracket syntax and custom index arguments, like an array. It is a property-like member with get and optionally set accessors, useful when a type naturally represents a collection, matrix, range, or keyed view.
Declaration and semantics
public sealed class Grid<T>
{
private readonly T[,] cells = new T[10, 10];
public T this[int row, int column]
{
get => cells[row, column];
set => cells[row, column] = value;
}
}
Indexers can take multiple parameters and overload by parameter types/count. They can be read-only, write-only (rare), virtual, or explicitly implemented through interfaces. The this keyword identifies the indexer; no ordinary member name is declared, though metadata uses Item by default. Index/Range types and ^/.. syntax work with types that expose the relevant pattern members or interfaces, not automatically with every custom indexer.
Indexers should define bounds, missing-key, and mutation behavior clearly. A dictionary-like indexer may throw for absent keys, while TryGetValue better models expected absence. An indexer getter that performs expensive I/O surprises callers.
Interview questions
- What is an indexer? An instance property accessed through bracket syntax.
- Can it have multiple indices? Yes; parameters may include multiple dimensions.
- Does
^1work for every indexer? No; support depends onIndex/length or interface patterns. - When prefer
TryGetValue? When missing keys are expected and should not be exceptional. - What is the default metadata name? Usually
Item, configurable withIndexerNameAttribute.