skip to content

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%

answer

  1. calling it only builds an object
  2. the first MoveNext starts it
  3. runs to the next yield
  4. a new enumerator restarts it

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.

solid answer

~40 s

Calling an iterator method only creates a compiler-generated object holding the arguments; no line of the body runs, so nothing is logged, opened or thrown yet. The body starts on the first `MoveNext()`, which `foreach` calls, and runs until the first `yield return`; each later `MoveNext()` resumes just after the previous `yield return` and runs to the next one, so production and consumption interleave one element at a time. The result is a recipe, not a stored collection: every `foreach` calls `GetEnumerator()` and gets an enumerator that starts the body from the top with the original arguments, repeating every side effect and every expensive read. If nobody enumerates, the body never runs at all. When you need the elements more than once, enumerate once into a `List<T>` and reuse it.

code

csharp · 23 lines
csharp
IEnumerable<int> evens = Evens(6);
Console.WriteLine("Evens(6) returned");

foreach (int n in evens)
    Console.WriteLine($"got {n}");

Console.WriteLine("second foreach:");
foreach (int n in evens)
{
    Console.WriteLine($"got {n}");
    break;
}

static IEnumerable<int> Evens(int limit)
{
    Console.WriteLine("body starts");
    for (int i = 0; i < limit; i += 2)
    {
        Console.WriteLine($"yielding {i}");
        yield return i;
    }
    Console.WriteLine("body ends");
}

go deeper

for a junior

Recall that calling an iterator does nothing visible; the code runs only when a foreach starts pulling elements, one yield return at a time.

for a middle

Explain the interleaving trace of MoveNext and yield return, and why a second enumeration starts the body again with the original arguments.

for a senior

Diagnose the production symptoms: an audit write that never happened because the result was not consumed, a database read repeated per enumeration, an exception surfacing inside the consumer's loop.

for a principal

Weigh laziness against predictability when setting team guidance: iterators stream cheaply but hide when work and failures happen, so decide where materialising once is the safer contract.

## Calling an iterator runs nothing When you call an iterator method, **none of the code you wrote in its body runs**. The compiler has replaced the body with a few lines that create an object of a generated class, copy the arguments into its fields, and return it. That object is the `IEnumerable<T>` the caller receives. So a call like `var evens = Evens(6);` prints nothing, opens nothing and throws nothing that the body would throw. This is **deferred execution of the body**: the work happens later, piece by piece, as someone pulls elements out. ## Each MoveNext resumes where it paused Pulling elements means calling `MoveNext()` on an enumerator, which is what `foreach` does for you. Trace the program below: ```csharp IEnumerable<int> evens = Evens(6); Console.WriteLine("Evens(6) returned"); foreach (int n in evens) Console.WriteLine($"got {n}"); static IEnumerable<int> Evens(int limit) { Console.WriteLine("body starts"); for (int i = 0; i < limit; i += 2) { Console.WriteLine($"yielding {i}"); yield return i; } Console.WriteLine("body ends"); } ``` 1. `Evens(6)` returns at once; the first line printed is `Evens(6) returned`. 2. `foreach` calls `GetEnumerator()`, then `MoveNext()`. Now the body starts: it prints `body starts`, then `yielding 0`, and pauses at `yield return 0`. 3. `MoveNext()` returns `true`; the loop prints `got 0`. 4. The next `MoveNext()` resumes after the `yield return`, increments `i`, prints `yielding 2`, and pauses again. 5. After `got 4`, the next `MoveNext()` leaves the loop, prints `body ends` and returns `false`. The body and the consumer **interleave**: one element is produced, consumed, then the next is produced. At no point does a full list exist. ## A second enumeration starts over The result of an iterator is not a stored collection; it is a recipe. Every `foreach` calls `GetEnumerator()`, and every enumerator starts the body **from the top**, with the original argument values. If the snippet above runs a second `foreach` over `evens`, the output shows `body starts` again and every side effect repeats. | Moment | What runs | |---|---| | `Evens(6)` is called | nothing from the body; an object is created | | first `MoveNext()` | the body, up to the first `yield return` | | each later `MoveNext()` | from just after the last `yield return` to the next one | | a second `foreach` | the body again, from the top, as a new enumeration | | nobody enumerates | nothing, ever | ## What never runs if nobody enumerates Because the body only runs on demand, an iterator that is called but never enumerated does none of its work: - **Side effects** such as logging, writing audit records, sending messages or incrementing counters never happen. - **Exceptions** the body would throw, including a `FileNotFoundException` from opening a file, are not raised at the call. They surface inside the caller's `foreach`, at the `MoveNext()` that reaches the failing line. - **Argument checks** written at the top of the body also wait for the first `MoveNext()`; the standard repair, an eager wrapper method, is covered with local functions. ## Practical consequences - Do not put essential side effects in an iterator and assume they happen when it is called; they happen only if the sequence is consumed. - Expensive iterators (database reads, file parsing, network calls) repeat their work for every enumeration. If you need the results twice, enumerate once into a collection with `ToList()` or `ToArray()` and reuse it, accepting that this holds every element in memory. - Partial consumption is cheap: a consumer that stops after three elements causes only the code up to the third `yield return` to run. - An exception from element five arrives after elements one to four have been processed, so the consumer may already have done partial work. - A `Console.WriteLine` or logger call inside the iterator is the quickest way to see all of this: the order of the printed lines shows exactly when the body runs relative to the consumer, as the output in this question shows. - Storing the result in a field and enumerating it from several places later reruns the body each time, possibly against data that has changed in between. The mental model interviewers look for is "an iterator is a paused method": calling it creates the pause point at the very start, and every `MoveNext()` lets it run to the next `yield return`.

  • If a C# iterator throws while producing its third element, when does the caller see the exception?
    Inside the caller's `foreach`, during the `MoveNext()` call that would have produced the third element, not when the iterator method was called. The loop body has already processed the first two elements, so partial work may be done; `finally` blocks around the failing line run as the exception leaves the iterator.
  • Do two GetEnumerator() calls on the same C# iterator result share a position?
    No. Each enumerator starts at the top of the body with the original argument values. The generated type reuses the enumerable object itself for the first `GetEnumerator()` call on the thread that created it, to save an allocation, but every later call gets a new instance, so two loops are fully independent.
  • How do you stop an expensive C# iterator from running its body twice when the results are needed more than once?
    Enumerate it once into a collection, for example with `ToList()` or `ToArray()`, and reuse that collection. It is a deliberate trade: the collection holds every element in memory and the laziness is gone, which is wrong for huge or endless sequences.

A cook who makes each course only when the waiter asks for it, and marks the recipe at the step reached. Nothing is cooked when the order is written down, and a second table ordering the same menu starts the recipe again from the first step.

  • The iterator body runs when the method is called, up to the first yield
  • A second foreach continues from where the first one stopped
  • An iterator caches its elements, so enumerating it twice is free
  • Exceptions from an iterator body are thrown at the call site
  • Side effects in an iterator happen even if nobody loops over it