skip to content

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