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

  1. What is an indexer? An instance property accessed through bracket syntax.
  2. Can it have multiple indices? Yes; parameters may include multiple dimensions.
  3. Does ^1 work for every indexer? No; support depends on Index/length or interface patterns.
  4. When prefer TryGetValue? When missing keys are expected and should not be exceptional.
  5. What is the default metadata name? Usually Item, configurable with IndexerNameAttribute.

References