Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 182 ยท Classes and Objects

Indexers and Custom Iterators

Learn C# indexers (this[]), multi-parameter and string indexers, Index and Range support, how foreach calls GetEnumerator, writing iterators with yield return and building a custom collection.

Arrays, lists and dictionaries share two abilities that look like language magic. You can reach an element with square brackets, items[3] or scores["ana"], and you can walk over every element with foreach. Neither is magic. Both are patterns that your own types can follow: an indexer gives a class the bracket syntax, and an iterator (a GetEnumerator method, usually written with yield return) makes it work in foreach, in LINQ and anywhere a sequence is expected.

This lesson builds a small Playlist collection step by step. You will write indexers (including ones with several parameters and non-integer keys), add ^1 and 1..3 support, see what foreach really expands to, write an enumerator by hand, and then replace it with a few lines of yield. It continues from classes, properties and the collection basics in lists.

Indexers: properties with parameters

An indexer is declared like a property, but its name is this and it takes parameters in square brackets. It has get and set accessors, and the keyword value works as in a property.

C# A first indexer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The real advantage over a public array is control. The indexer validates input, can compute results instead of storing them, and can be read-only (leave out set), write-only (rare) or have a private set. You may also use expression-bodied syntax for read-only indexers: public int this[int i] => _data[i];.

An indexer is compiled to a pair of methods called get_Item and set_Item, and a class can have several indexers as long as their parameter lists differ (overloads). The default name Item can be changed with [IndexerName("Name")], mostly useful for COM and VB interop.

Indexers with other key types and several parameters

The parameter does not have to be an int. Any type works, and you can declare more than one parameter. Use that for a grid (grid[row, col]) or a lookup by name.

C# Grid and string indexers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Settings shows a useful pattern: reading a missing key returns null (note the nullable return type string?) instead of throwing the KeyNotFoundException that a Dictionary throws, and assigning null removes the entry. Choose and document one convention for missing keys; surprising behaviour is the main danger of indexers.

An indexer should be cheap and free of surprises. Callers assume x[i] is about as fast as an array access and has no side effects. If your lookup does a database call or heavy work, use a method (Find(key), GetAsync(id)) so the cost is visible.

Supporting ^1 and ranges

You have seen list[^1] and array[1..4] in the lesson on ranges and indices. Your own type gets that syntax almost for free, because of a pattern-based rule. If a type has

  • a Count or Length property (an int), and
  • an int indexer,

then x[^n] works: the compiler rewrites it to x[x.Count - n]. If, in addition, it has a method Slice(int start, int length), then x[a..b] works and calls Slice(a, b - a). No interface is involved.

C# Index and Range support by pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Also valid is declaring indexers that take Index and Range directly: public string this[Index i] => ... and public Playlist this[Range r] => .... Then you decide how to translate positions, using i.GetOffset(Count) and r.GetOffsetAndLength(Count). Use the pattern approach for simple cases and the explicit one when you need full control.

What foreach really does

foreach is syntactic sugar. For a collection items, the compiler looks for a public method GetEnumerator() (not necessarily from an interface!) and generates code equivalent to:

C#
var enumerator = items.GetEnumerator();
try
{
    while (enumerator.MoveNext())
    {
        var item = enumerator.Current;
        // loop body
    }
}
finally
{
    (enumerator as IDisposable)?.Dispose();
}

So a type works in foreach if its GetEnumerator() returns something with a bool MoveNext() method and a Current property. Implementing IEnumerable<T> is the standard way to promise this, and it is required to pass your collection to LINQ and most APIs. The enumerator state machine is separate from the collection, so two loops can walk the same collection independently.

C# Writing the enumerator by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This is a lot of ceremony for counting down: a nested class with state, two Current properties, Reset and Dispose. Everything in it, though, is what the compiler generates for you when you use yield.

Iterators with yield return

A method returning IEnumerable<T> (or IEnumerator<T>, or the non-generic ones) that contains yield return is an iterator. The compiler turns it into a state machine class like the one above. Execution is lazy: no code in the method runs until the caller asks for the first element, and it pauses after each yield return until the next element is requested.

C# yield return is lazy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output interleaves producer and consumer: the line "creating the sequence", then "nothing has run yet", then "iterator starts", and after that producing and consumer got lines alternate. Laziness lets you represent infinite or very large sequences, stop early (with break or LINQ's Take), and avoid building a whole list in memory.

Related keywords:

  • yield break; ends the sequence early.
  • You cannot use yield inside a try with a catch, in a finally, or in methods with ref/out parameters. A try/finally is fine, and the finally block runs when the loop ends or is abandoned (the enumerator is disposed).
  • Argument validation is deferred too. If you throw for bad arguments inside the iterator, the exception appears at the first MoveNext, not at the call. Professionals therefore split the method in two: a normal public method that validates and a private iterator that does the work.
C# Validate eagerly, iterate lazily

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Putting it together: a custom collection

Here is a generic ring buffer that keeps the last N items. It combines everything: an indexer with bounds checks, the Count property so ^1 works, and an iterator for foreach and LINQ.

C# RingBuffer with an indexer and an iterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The buffer holds c d e after five additions. Notice how little code the iterator needs, and that Select and Reverse come from LINQ for free once the type implements IEnumerable<T>. (Reverse here is the LINQ extension, which buffers the sequence; it does not need a special method.)

Mutating while enumerating

The built-in collections throw InvalidOperationException ("Collection was modified") if you add or remove during a foreach, using an internal version counter. Your own collection does not do that automatically. If it matters, keep a _version field that every mutator increments, remember it when the enumerator starts and compare it on each MoveNext. For a small internal type, documenting "don't modify while iterating" is often enough.

Iterators in practice

  • Return IEnumerable<T> from a method when the caller only needs to read the elements once. Return a List<T> or T[] when they may index or count (see collection interfaces).
  • Remember that each foreach over an iterator method re-runs it from the start. Expensive generation done twice is a classic performance bug. Materialize with .ToList() if you need a snapshot.
  • Prefer exposing existing collections (IReadOnlyList<T>) over writing an enumerator, and write custom iterators for trees, files, paged data, generators and anything that is naturally lazy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How is an indexer declared in a class?

    An indexer uses the keyword this followed by parameters in square brackets and accessor blocks like a property.
  2. 2. What must a type have so that x[^1] works without writing an Index indexer?

    The compiler rewrites x[^n] to x[x.Count - n] when the type has an accessible Count/Length and an int indexer. Slice is only needed for ranges.
  3. 3. When does the body of an iterator method (one with yield return) start running?

    Iterators are lazy. Calling the method only creates the state machine; code runs on MoveNext.
  4. 4. Why do experienced developers often split a public iterator method into a validating wrapper and a private iterator?

    Because of lazy execution, an exception for a bad argument would appear late and far from the buggy call. A wrapper validates immediately.
  5. 5. Which is NOT allowed inside an iterator method?

    yield return cannot appear in a try block with a catch clause, nor inside a finally. A try with only finally is fine.

Summary

  • An indexer (this[...]) gives a type bracket syntax; it can have several parameters of any type, be read-only, and is compiled to get_Item/set_Item.
  • Keep indexers cheap and predictable, and decide how missing keys behave.
  • A Count/Length plus an int indexer enables ^n; adding Slice(int, int) enables ranges.
  • foreach calls GetEnumerator(), MoveNext() and Current; implement IEnumerable<T> to work with LINQ.
  • yield return writes the enumerator state machine for you, lazily; use yield break to stop early.
  • Validate arguments in a wrapper method, and remember that every foreach re-runs an iterator.

Next: Extension Methods and Extension Members