Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Keywords and Statements

The yield statement

Reference for C# yield: writing iterator methods with yield return and yield break, lazy evaluation, argument validation, try restrictions and async iterators.

yield turns a method into an iterator. yield return value; hands one element to the caller and pauses the method; when the caller asks for the next element the method resumes right after the yield return. yield break; ends the sequence. The compiler builds a state machine class for you, so you never write an enumerator by hand.

An iterator must return IEnumerable<T>, IEnumerable, IEnumerator<T> or IEnumerator (or IAsyncEnumerable<T> in an async method). Nothing in the body runs until the first MoveNext(), which means iterators are lazy and can describe infinite sequences.

C#
static IEnumerable<int> Evens(int limit)
{
    for (int i = 0; i <= limit; i += 2)
    {
        yield return i;
    }
}

Try it

C# Lazy sequences

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# yield break and delayed validation

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#
yield return expression;
yield break;
Name Description
expression A value convertible to the element type T of the iterator's return type.

Returns: the method returns an IEnumerable<T> or IEnumerator<T> object immediately, without executing the body.

Errors: yield cannot appear in a method with ref, out or in parameters (CS1623), in an unsafe block, in a lambda, or in a finally block (CS1625). yield return is not allowed inside a try block that has a catch clause (CS1626); a try/finally is fine. Mixing return value; with yield gives CS1622.

Usage notes

  • Lazy and re-runnable. Each call to GetEnumerator() starts the body again from the top, so enumerating twice repeats side effects.
  • Deferred validation. Argument checks run on the first MoveNext(), not at the call. Split the method as in the second example so errors surface immediately. LINQ operators work this way too.
  • Memory. Elements are produced one at a time, so you can stream huge files or infinite sequences without building a list.
  • Cleanup. A finally block in an iterator runs when the loop finishes or when the consumer disposes the enumerator early (for example with break in a foreach).
  • Delegating: there is no yield foreach; loop over the inner sequence and yield return each item.
  • Async iterators combine async, yield return and IAsyncEnumerable<T>, and are consumed with await foreach.
  • Cost: a small heap object per call; for tiny, hot loops a plain array or List<T> can be faster.