Iterator disposal and exceptions
Iterator disposal and exceptions
A lazy iterator can hold resources and encounter errors during enumeration. The caller must dispose the enumerator when it stops early, and validation placed inside an iterator body may run later than expected. Design resource ownership and error timing deliberately.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Dispose on early exit
An iterator can use try/finally around yield return. A foreach over a generic enumerable disposes its enumerator when the loop exits, including a break. A finally surrounding a suspended yield is not executed just because the next value was returned; it executes when control leaves the protected region or the suspended enumerator is disposed.
using System;using System.Collections.Generic;foreach (int n in Readings()){ Console.WriteLine(n); break;}Console.WriteLine("After loop");static IEnumerable<int> Readings(){ Console.WriteLine("Open"); try { yield return 4; yield return 8; } finally { Console.WriteLine("Close"); }}The loop stops after the first value, but disposal executes the finally block. The example uses messages rather than an actual file.
Expected output (reasoned, not executed):
Open4CloseAfter loopObserve deferred failures
Exceptions inside an iterator are raised when execution reaches the failing statement, often during MoveNext. Catch around enumeration, not only around query construction. Do not put yield return in a catch or finally block, or in a try block that has catch clauses.
using System;using System.Collections.Generic;var source = Read();Console.WriteLine("Created");try{ foreach (int n in source) Console.WriteLine(n);}catch (InvalidOperationException) { Console.WriteLine("Read failed"); }static IEnumerable<int> Read(){ yield return 1; throw new InvalidOperationException("Synthetic read failure");}Constructing the enumerable succeeds. The exception propagates from the second advance, after the first item was consumed.
Expected output (reasoned, not executed):
Created1Read failedValidate before creating the iterator
Use an ordinary wrapper method for eager argument checks, and return a separate local iterator for delayed work. The wrapper must not itself contain yield. This separates public API argument validation from errors during later enumeration.
using System;using System.Collections.Generic;using System.Linq;try { _ = Bounded(-1); }catch (ArgumentOutOfRangeException) { Console.WriteLine("Invalid count"); }Console.WriteLine(string.Join(",", Bounded(3)));static IEnumerable<int> Bounded(int count){ if (count < 0 || count > 100) throw new ArgumentOutOfRangeException(nameof(count)); return Generate(); IEnumerable<int> Generate() { for (int i = 0; i < count; i++) yield return i; }}The ordinary wrapper checks the argument before returning a sequence. The local function supplies the lazy values.
Expected output (reasoned, not executed):
Invalid count0,1,2Common mistakes and edge cases
Do not rely on garbage collection to close a resource held by an abandoned iterator. Use foreach or explicitly dispose a manually obtained enumerator, e.g. using var cursor. A using inside the iterator can hold the resource across yield points until cleanup. If the sequence is never started, code inside the body has not acquired its resource. Normal cleanup rules do not guarantee recovery after abrupt process termination.
Practice and recap
Modify Readings to log Open and Close, consume zero values without advancing, then consume one value and break, then consume all values in separate traversals. Predict each trace.
Hint: A sequence assignment alone does not enter the body; foreach disposes when leaving.
Learning objective: Predict cleanup when enumeration stops early. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Iterator disposal and exceptions — knowledge check
Apply the lesson concepts to the following scenarios.
What closes a suspended iterator on foreach break?
When is an exception inside a lazy iterator usually observed?
Where is yield return allowed in these examples?
How can argument validation be made eager?
What happens if an iterator body is never entered?