Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Classes and Object-Oriented Concepts

Iterators in C#

Reference for C# iterators: write lazy sequences with yield return and yield break, custom GetEnumerator, deferred execution, argument checks and async iterators.

An iterator is a method, property getter or indexer getter that returns IEnumerable<T>, IEnumerator<T> (or the non-generic versions, or IAsyncEnumerable<T>) and uses yield return to hand out values one at a time. The compiler turns the body into a state machine class. Execution pauses at each yield return and resumes from there when the consumer asks for the next item.

That makes sequences lazy: values are computed on demand, an infinite sequence is fine, and a consumer that stops early does no extra work. Nothing in the body runs when you call the method, only when you start enumerating.

C#
static IEnumerable<int> Count(int to)
{
    for (int i = 1; i <= to; i++) yield return i;
}

Try it

C# Pausing and resuming

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.

C# Infinite sequences, GetEnumerator and eager argument checks

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.

Syntax

C#
IEnumerable<T> Method() { yield return value; yield break; }
IEnumerator<T> GetEnumerator() { yield return value; }
public IEnumerable<T> Items { get { yield return a; yield return b; } }
async IAsyncEnumerable<T> StreamAsync([EnumeratorCancellation] CancellationToken ct = default)
{
    await Task.Delay(1, ct);
    yield return value;
}
Statement Description
yield return x; Produces x as the next element and suspends the method.
yield break; Ends the sequence. Reaching the end of the body does the same.
Return type IEnumerable<T>, IEnumerator<T>, IEnumerable, IEnumerator, or IAsyncEnumerable<T> / IAsyncEnumerator<T>.

Restrictions: an iterator cannot have ref, in or out parameters (CS1623), cannot contain yield return inside a try block that has a catch clause (CS1626), and cannot yield return inside a finally (CS1625). Unsafe code is not allowed in them.

Usage notes

  • Deferred execution. The body, including argument checks, runs on the first MoveNext(). Use a non-iterator wrapper that validates and then returns a local iterator (as in Eager).
  • Each enumeration restarts. Calling foreach twice on an IEnumerable<T> iterator runs the body twice. Cache with ToList() when the work is expensive or has side effects.
  • try/finally works. A finally in an iterator runs when the enumeration finishes or is disposed early (for example by break in foreach). That is how resources inside an iterator get released.
  • State lives in fields. Locals of an iterator become fields of the generated class, so they persist across yield return and are kept alive while the enumerator is.
  • Memory is O(1) for streaming pipelines; materializing with ToList() costs O(n).
  • Recursion. Recursive iterators (tree walks) re-yield each element through every level: yield return in a loop of depth d costs O(d) per element. For deep trees use an explicit stack.
  • Single-pass sources. An iterator over a stream or a network reader can often only be enumerated once.
  • Async iterators (await foreach) are covered in IAsyncEnumerable.