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.
static IEnumerable<int> Count(int to) { for (int i = 1; i <= to; i++) yield return i; }
Try it
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.
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
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 inEager). - Each enumeration restarts. Calling
foreachtwice on anIEnumerable<T>iterator runs the body twice. Cache withToList()when the work is expensive or has side effects. try/finallyworks. Afinallyin an iterator runs when the enumeration finishes or is disposed early (for example bybreakinforeach). 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 returnand 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 returnin a loop of depthdcosts 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.