skip to content

Yield-Based Methods

An iterator method runs nothing until the first MoveNext, pauses at each yield return, and runs finally blocks on Dispose. Interviewers ask when the body actually runs.

on this pageshow

explore

questions

5

In a C# method that returns IEnumerable<T>, what do yield return and yield break do, and why is a plain return rejected?

level: juniorimportance: must knowfreq 70%

answer

  1. one element per request
  2. the method becomes an iterator
  3. ending the sequence early
  4. CS1622 on any return

basics

~20 s

yield return hands the caller the next element and pauses the method until another is requested; yield break ends the sequence. Any yield makes the method an iterator, so a return statement, even a bare return;, is error CS1622.

solid answer

~40 s

A method whose body contains `yield return` or `yield break` is an **iterator**; a synchronous one must return `IEnumerable<T>`, `IEnumerable`, `IEnumerator<T>` or `IEnumerator` (anything else is CS1624). Each `yield return expr` produces one element and suspends the method; the next `MoveNext()` resumes it on the following line with its locals intact. `yield break` ends the sequence at once, exactly like reaching the closing brace, and enclosing `finally` blocks still run. Because the compiler turns the body into a generated enumerator, a `return` statement has nothing to hand back: `return list;` and even a bare `return;` both fail with CS1622, which tells you to use `yield return` or `yield break`. So one method either builds and returns a collection or yields its elements, never both.

code

csharp · 12 lines
csharp
foreach (string id in FirstIds(["a1", "b2", "", "c3"]))
    Console.WriteLine(id);

static IEnumerable<string> FirstIds(string[] rows)
{
    foreach (string row in rows)
    {
        if (row.Length == 0)
            yield break;      // ends the sequence; nothing after this runs
        yield return row.ToUpperInvariant();
    }
}

go deeper

for a junior

Recall the two statements: yield return produces one element and pauses, yield break ends the sequence. Know that a method with any yield cannot use return at all.

for a middle

Explain that the method becomes an iterator whose return type must be one of the four iterator interfaces, and that yield break still runs enclosing finally blocks.

for a senior

Show you can read an unfamiliar iterator correctly: distinguish break from yield break inside loops, and spot a method that tries to mix returning a ready collection with yielding.

for a principal

Frame iterators as a design choice: yielding keeps a method lazy and streaming, returning a built collection makes it eager. Be ready to say which one an API should expose and why.

## What makes a method an iterator A C# method becomes an **iterator** the moment its body contains a `yield return` or a `yield break` statement. Nothing else marks it: there is no attribute or modifier to add. The compiler then requires the declared return type to be one of the four **iterator interface types**: - `IEnumerable<T>` or the non-generic `IEnumerable`, for a sequence the caller can loop over with `foreach`; - `IEnumerator<T>` or the non-generic `IEnumerator`, typically for a `GetEnumerator()` method on your own collection type. Declaring any other return type, such as `List<int>`, fails with **CS1624**: "The body of 'Numbers()' cannot be an iterator block because 'List<int>' is not an iterator interface type". (Methods returning `IAsyncEnumerable<T>` are async iterators, a separate subject.) ## yield return: one element, then pause `yield return expression;` produces exactly one element. The method does not run to the end and hand back a finished collection; it **suspends** at that statement. The caller's `foreach` processes the element, asks for the next one, and the method resumes on the line right after the `yield return`, with every local variable still holding its value. ```csharp static IEnumerable<string> FirstIds(string[] rows) { foreach (string row in rows) { if (row.Length == 0) yield break; // ends the sequence yield return row.ToUpperInvariant(); } } ``` Called with `["a1", "b2", "", "c3"]`, a `foreach` over `FirstIds` prints `A1` and `B2`, then stops: the empty row ends the sequence and `c3` is never read. ## yield break: ending the sequence `yield break;` ends the iteration immediately. It is the iterator's equivalent of an early exit, and it behaves like reaching the method's closing brace: 1. Control leaves the iterator body; any enclosing `finally` blocks run, including the ones a `using` statement generates. 2. The current `MoveNext()` call returns `false`. 3. The caller's `foreach` ends normally. Nothing is thrown. Code after an unconditional `yield break` is unreachable; the compiler only warns about it (CS0162, "Unreachable code detected") and it never runs. ## Why return is an error (CS1622) An iterator does not return a value in the ordinary sense. The compiler rewrites the whole body into a generated enumerator class, and the method itself just creates and returns that object. A `return` statement has no meaning inside the rewritten body, so the compiler rejects every form of it: - `return new[] { 2, 3 };` inside a method that also yields fails with **CS1622**: "Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration." - A bare `return;` fails with the same CS1622 on the SDK 10.0.401 compiler. Many developers expect it to work because it returns nothing; it does not. The practical rule: a method either **builds and returns** a collection, or it **yields** elements one by one. It cannot mix the two. If part of the logic wants to return a ready-made sequence, write `foreach (var x in ready) yield return x;` or split the logic into two methods. ## Quick reference | Statement | Effect inside an iterator | |---|---| | `yield return x;` | produce `x`, suspend until the next `MoveNext()` | | `yield break;` | end the sequence; enclosing `finally` blocks run | | reaching the closing brace | same as `yield break;` | | `return x;` or `return;` | compile error CS1622 | | `break;` inside a loop | leaves that loop only; the iterator keeps running after it | ## Common mistakes - Thinking `yield return` collects items into a hidden list that is returned at the end. The elements are produced on demand, one per `MoveNext()`. - Using `break;` to end the sequence from inside a loop: it only exits the loop, and any `yield return` after the loop still runs. - Throwing an exception to stop iteration. `yield break;` is the normal, silent way to finish. - Forgetting that a lambda cannot be an iterator: `() => { yield return 1; }` fails with CS1621. A local function can be one. Interviewers use this question to confirm you know the vocabulary of iterators and that the method's shape changes completely once it contains a `yield`: from then on it is a producer of elements on demand, not a function that computes a result and hands it back.

  • Can a C# iterator return IEnumerator<T> instead of IEnumerable<T>, and where would you write one?
    Yes. `IEnumerator<T>` and `IEnumerator` are iterator return types too. The usual place is `public IEnumerator<T> GetEnumerator()` on your own collection type, written with `yield return`, so `foreach` works without a hand-written enumerator class. The caller then gets an enumerator directly rather than a sequence; each call to `GetEnumerator()` runs the method again and starts a fresh walk.
  • Does yield break inside a try block skip the enclosing finally in a C# iterator?
    No. `yield break` leaves the iterator body the way `return` leaves an ordinary method, so every enclosing `finally` runs first, including the one a `using` statement generates. Only then does `MoveNext()` return `false` and the caller's `foreach` end.
  • Can a lambda expression in C# contain yield return?
    No. The compiler rejects it with CS1621, "The yield statement cannot be used inside an anonymous method or lambda expression". A local function, by contrast, can be an iterator, which is the usual way to keep a small iterator next to the code that uses it.

  • yield return adds items to a hidden list that is returned at the end
  • yield break throws an exception to stop the caller's loop
  • A bare return; is fine in an iterator because it returns no value
  • An iterator can declare List<T> as its return type
  • break; inside the loop ends the whole iterator sequence
open as a page

In C#, when does the body of an iterator method actually start running, and what happens if its result is enumerated twice?

level: middleimportance: must knowfreq 68%

basics

~20 s

Calling an iterator runs none of its body; it only returns an object. The body starts on the first MoveNext, pauses at each yield return, and a second foreach runs it again from the top, side effects included.

open as a page

A C# iterator opens a log file and closes it in finally; when does that finally run if a foreach breaks after 20 errors?

level: middleimportance: should knowfreq 50%

basics

~20 s

At the break: foreach calls Dispose on the iterator's enumerator, and the generated Dispose runs the finally blocks around the paused yield return, closing the file. Code that calls MoveNext by hand without disposing leaves the file open.

open as a page

What does the C# compiler generate for an iterator method returning IEnumerable<T>, and what jobs do its state and hoisted fields do?

level: middleimportance: should knowfreq 40%

basics

~20 s

A private nested sealed class implementing IEnumerable<T>, IEnumerator<T> and IDisposable. Parameters and locals that live across a yield become fields, a state field records where the body paused, and MoveNext jumps back there; the method itself just creates the object.

open as a page

A C# iterator wraps yield return int.Parse(row) in try/catch and fails with CS1626; why, and how do you restructure it to skip bad rows?

level: seniorimportance: should knowfreq 35%

basics

~20 s

C# forbids yield return inside a try block that has a catch (CS1626) and inside a catch block (CS1631). Move the try/catch into an ordinary helper that parses one row and reports success, then yield outside the try.

open as a page