A C# iterator opens a log file and closes it in finally; when does that finally run if a foreach breaks after 20 errors?
answer
- foreach hides a try/finally
- Dispose on the enumerator
- pending finally blocks run
- manual MoveNext needs using
basics
~20 sAt 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.
solid answer
~40 s`foreach` wraps its loop in a hidden `try`/`finally` that calls `Dispose()` on the enumerator however the loop ends: completion, `break`, `return` or an exception from the loop body. For an iterator, that enumerator is the compiler-generated state machine, and its `Dispose()` runs the `finally` blocks (including `using` blocks) that enclose the `yield return` it is paused at, then marks it finished; it never resumes the loop. So on the 20th error the `break` triggers `Dispose()`, the iterator's `finally` disposes the `StreamReader`, and the file is closed before the next statement after the loop. The leak case is manual enumeration: a helper that calls `GetEnumerator()` and `MoveNext()` without `Dispose()` leaves the iterator paused inside the `try`, so the file stays open until a garbage collection finalizes the handle. Wrap such enumerators in `using`.
code
csharp · 35 linesstring path = Path.Combine(Path.GetTempPath(), "app.log");
File.WriteAllLines(path, Enumerable.Range(1, 100).Select(i => $"{(i % 3 == 0 ? "ERROR" : "INFO")} event {i}"));
IEnumerable<string> lines = ReadLog(path); // nothing opened yet
Console.WriteLine("ReadLog called");
int errors = 0;
foreach (string line in lines)
{
if (!line.StartsWith("ERROR")) continue;
if (++errors == 3) break; // foreach calls Dispose here
}
Console.WriteLine($"stopped after {errors} errors");
IEnumerator<string> e = lines.GetEnumerator();
e.MoveNext(); // opens the file again
Console.WriteLine($"manual: {e.Current}"); // no Dispose: the file stays open
Console.WriteLine("end of program");
static IEnumerable<string> ReadLog(string path)
{
Console.WriteLine("opening log");
StreamReader reader = File.OpenText(path);
try
{
string? line;
while ((line = reader.ReadLine()) is not null)
yield return line;
}
finally
{
reader.Dispose();
Console.WriteLine("log closed");
}
}go deeper
Recall that foreach always disposes its enumerator, and that a finally or using inside an iterator is how the iterator cleans up after itself.
Explain the foreach expansion and what the generated Dispose does: run the finally blocks around the paused yield, mark the iterator finished, run nothing else.
Spot the leak in review: manual GetEnumerator and MoveNext without using, or an enumerator stored and abandoned. Know the order of cleanup and catch when the consumer throws.
Set the rule that iterators which acquire resources must release them in finally or using, and that hand-written enumeration is always disposed, so early-stopping consumers stay safe.
## The scenario A log reader is a natural iterator: it opens a file, reads it line by line and yields each parsed line, so a caller never holds the whole file in memory. A dashboard consumes it and stops after the first 20 errors with `break`. The question is when the file gets closed, and the answer depends on understanding what `foreach` emits and what the compiler-generated `Dispose()` does. ```csharp static IEnumerable<string> ReadLog(string path) { StreamReader reader = File.OpenText(path); try { string? line; while ((line = reader.ReadLine()) is not null) yield return line; } finally { reader.Dispose(); // must run even if the caller stops early } } ``` A `using` declaration (`using StreamReader reader = File.OpenText(path);`) compiles to the same `try`/`finally`, and iterators allow it. ## What foreach really emits For an `IEnumerable<T>`, a `foreach` loop expands to roughly this shape: ```csharp IEnumerator<string> e = lines.GetEnumerator(); try { while (e.MoveNext()) { string line = e.Current; /* loop body */ } } finally { e.Dispose(); } ``` The `finally` means `Dispose()` is called **however the loop ends**: running out of elements, `break`, `return`, `goto` out of the loop, or an exception thrown from the loop body. ## What the generated Dispose does The enumerator is the compiler-generated state machine. Its `Dispose()` looks at where the iterator is paused: - If the paused `yield return` sits inside one or more `try` blocks that have `finally` clauses (including `using` blocks), it **runs those finally blocks**, innermost first. - It then marks the iterator as finished, so later `MoveNext()` calls return `false`. - It does **not** resume the loop or run any code after the paused `yield return`; only the pending cleanup runs. - If the iterator never started, or already finished, there is nothing to run. ## Trace of the dashboard 1. `ReadLog(path)` is called: nothing happens yet, the file is not opened. 2. The dashboard's `foreach` calls `MoveNext()`: the body opens the file and yields the first line. 3. Lines flow one at a time; the dashboard counts errors. 4. On the 20th error the loop executes `break`. `foreach`'s hidden `finally` calls `Dispose()`. 5. `Dispose()` runs the iterator's `finally`, which disposes the `StreamReader` and closes the file, before control reaches the statement after the loop. ## Where the finally does not run The cleanup is tied to `Dispose()`, so anything that skips `Dispose()` skips the cleanup: - **Manual enumeration without disposal.** A helper that calls `GetEnumerator()` and `MoveNext()` once to read the first line, and never calls `Dispose()`, leaves the iterator paused inside the `try`. The file stays open until a garbage collection finalizes the underlying file handle; the iterator object itself has no finalizer. The fix is `using IEnumerator<string> e = ReadLog(path).GetEnumerator();`, or calling `First()`, which disposes its enumerator. - **Never enumerated.** If nobody loops, the file is never opened, so there is nothing to close; this is a correct outcome, not a leak. - **Paused outside any try.** If the iterator is paused at a `yield return` that is not inside a `try`/`finally`, `Dispose()` has no cleanup to run. | How the consumer leaves | Does the iterator's finally run? | |---|---| | `foreach` reads every line | yes, when the body reaches its end | | `break` or `return` inside `foreach` | yes, through `Dispose()` | | exception thrown in the loop body | yes, before the exception reaches the caller's `catch` | | manual `MoveNext()` with no `Dispose()` | no | | never enumerated | nothing was opened | An exception thrown by the iterator itself, such as an `IOException` from `ReadLine()`, also runs the enclosing `finally` as it propagates out of `MoveNext()`. ## Why interviewers ask it The question separates people who think of an iterator as a loop that "finishes" from those who know the consumer controls its lifetime. An iterator that opens a file, a database reader or a network stream hands the decision of when to stop to whoever enumerates it; the iterator's only lever is to put its cleanup where `Dispose()` will find it. The production habit that follows: put cleanup for resources an iterator opens in `finally` or `using` inside the iterator, and treat every hand-written `GetEnumerator()` call as a disposable that needs `using`.
- If the dashboard's foreach body throws, does the C# iterator's finally still run, and in what order?Yes. The exception leaves the loop through `foreach`'s hidden `finally`, which calls `Dispose()` on the enumerator; that runs the iterator's pending `finally` blocks first. Only then does the exception reach the caller's `catch`, so the file is already closed when the handler runs.
- Is a using declaration inside a C# iterator safe across yield return?Yes. `using` compiles to a `try`/`finally` with no `catch`, which iterators allow. The resource stays open while the iterator is paused at a `yield return` and is disposed when the body completes, reaches `yield break`, or the enumerator is disposed early by the consumer.
- A helper reads only the first line by calling GetEnumerator() and MoveNext() on the log iterator; what must it add?A `using`: `using IEnumerator<string> e = ReadLog(path).GetEnumerator();`. Without it nothing calls `Dispose()`, the iterator stays paused inside its `try`, and the file stays open until the handle is finalized. Calling `First()` is simpler and also correct, because it disposes the enumerator it creates.
- The finally runs only if the iterator reaches its last line
- Breaking out of foreach leaves the file open until garbage collection
- You must call Reset on the enumerator to release the file
- The file is opened when ReadLog is called, even if nobody loops
- Dispose resumes the iterator and finishes the remaining lines first