Iterator intent (traverse without exposing structure), IEnumerable<T>/IEnumerator<T> roles, foreach pattern binding, external vs internal iteration, yield return for custom traversals (tree walking), IAsyncEnumerable<T> for paged APIs with await foreach and [EnumeratorCancellation], LINQ over async streams in .NET 10, and gotchas: deferred execution, multiple enumeration, modifying during enumeration and disposal.
The Iterator pattern lets code walk through a collection one element at a time without knowing how it's stored: an array, a tree or pages from an API all look the same to the caller.
In .NET:
IEnumerable<T> is the collection (it hands out an iterator); IEnumerator<T> is the iterator (MoveNext, Current, Dispose). foreach uses them for you.yield return makes the compiler write the iterator, so a depth-first tree walk is a few lines.IAsyncEnumerable<T> with await foreach does the same for items that arrive asynchronously, like paged API results.The gotcha is deferred execution: an iterator does nothing until you enumerate it, and repeats the work every time you enumerate it. Modifying a List<T> while looping over it throws.
"The Iterator pattern separates walking through a collection from the collection itself. The caller asks for the next item until there are no more, and doesn't need to know whether it's an array, a linked list, a tree or a REST API that returns pages. In .NET this is built in.
IEnumerable<T>means 'you can iterate me', and its one method,GetEnumerator, returns anIEnumerator<T>, which is the actual iterator:MoveNextadvances,Currentis the item, andDisposecleans up.foreachis just syntax for calling those, including disposing the enumerator at the end, which matters when it holds a file or a database reader open.The part I use most is
yield return. If I have a category tree and want callers to loop over every category, I write a method that returnsIEnumerable<Category>, walks the tree with a stack and yields each node. The compiler generates the state machine, and callers justforeach. They never see the children lists, so I can change the structure later. For asynchronous sources I useIAsyncEnumerable<T>: a client method can fetch page one, yield its items, fetch page two only when the caller wants more, and the caller writesawait foreach. In .NET 10, LINQ operators likeWhereandSelectwork directly onIAsyncEnumerable<T>becauseSystem.Linq.AsyncEnumerableis part of the core libraries now.The mistake I see is forgetting that iterators are lazy. Nothing runs when you call the method; it runs when you enumerate, and it runs again every time you do. So calling
Count()and thenforeachon an iterator that hits an API makes every request twice. The other classic is removing items from aList<T>inside aforeachover it, which throws 'Collection was modified'. An iterator is a recipe for producing items, not a list of them; materialise it withToList()when you need to go through it more than once."
| GoF role | .NET type | Responsibility |
|---|---|---|
| Aggregate | IEnumerable<T> |
Creates an iterator (GetEnumerator) |
| Iterator | IEnumerator<T> |
MoveNext, Current, Dispose |
| Async aggregate | IAsyncEnumerable<T> |
GetAsyncEnumerator(CancellationToken) |
| Async iterator | IAsyncEnumerator<T> |
MoveNextAsync, Current, DisposeAsync |
| Symptom | Cause | Fix |
|---|---|---|
| API or database called twice | Iterator enumerated twice (Count() then foreach) |
ToList() once and reuse |
InvalidOperationException: Collection was modified |
Adding or removing from a List<T> during foreach |
Iterate a copy, or use RemoveAll |
| Result includes items added later | Query defined before the source changed, enumerated after | Materialise at the point you mean |
ObjectDisposedException |
Iterator enumerated after its DbContext or stream was disposed |
Enumerate inside the scope, or materialise first |
A sync job called products.Count() for logging and then foreach over an IAsyncEnumerable paged client, so it fetched every page of a 40,000-product catalogue twice and hit the supplier's rate limit. Streaming once with await foreach and counting as it went halved the run time from about 18 minutes to 9 and removed the 429 errors.
Checks that the candidate recognises IEnumerable/IEnumerator as the Iterator pattern, can write custom iterators, and understands deferred execution.
Green flags
foreach does.yield return for a custom traversal.IAsyncEnumerable<T> and await foreach for paged or streamed data.Red flags
IEnumerable<T> always holds its data in memory.foreach.Client ── foreach ──▶ IEnumerable<T>.GetEnumerator() ──▶ IEnumerator<T>
MoveNext() : bool
Current : T
Dispose()
Concrete aggregates: List<T>, T[], Dictionary<K,V>, your Category tree, a paged API client
The client depends only on the two interfaces. Each aggregate can iterate however suits its storage, and can offer several iterators (in-order, depth-first, breadth-first) through different methods.
foreach bindsforeach is pattern-based: the compiler looks for an accessible GetEnumerator() returning a type with MoveNext() and Current, and only falls back to the interfaces if needed. List<T> returns a struct List<T>.Enumerator, so foreach over a List<T> variable allocates nothing; over an IEnumerable<T> variable it boxes the enumerator. The loop is wrapped in try/finally that disposes the enumerator, which is what closes files or readers when you break early.
yield returnA method returning IEnumerable<T> that contains yield return is compiled into a class implementing both IEnumerable<T> and IEnumerator<T>, with a state field and the method's locals as fields. Each MoveNext runs until the next yield return (or the end). Consequences: nothing runs at the call, argument validation is deferred until the first MoveNext, and finally blocks run on Dispose.
foreach, MoveNext) and controls the pace.List<T>.ForEach(action), Rx IObservable<T>).External iteration composes with LINQ and can stop early; internal iteration is the Observer side of the same coin.
IAsyncEnumerable<T>An async method that returns IAsyncEnumerable<T> and uses yield return produces an async iterator. Callers use await foreach, and MoveNextAsync returns a ValueTask<bool>. Cancellation flows through GetAsyncEnumerator(token): mark the iterator's token parameter with [EnumeratorCancellation] so .WithCancellation(token) at the call site reaches it. ASP.NET Core can stream an IAsyncEnumerable<T> result as JSON, and EF Core exposes AsAsyncEnumerable(). Since .NET 10, LINQ over async streams ships in the box as System.Linq.AsyncEnumerable.
Returning IEnumerable<T> from a domain object (instead of its List<T> field) prevents callers from adding to or clearing the collection, and lets you change the storage later. Prefer IReadOnlyList<T> or IReadOnlyCollection<T> when callers need a count or indexing and the data is already materialised.
DescendantsAndSelf() iterator for a tree and add a breadth-first one using a Queue<T>.Console.WriteLine at the top of an iterator method and call it without enumerating; nothing prints.IAsyncEnumerable<T> paged client against a fake API and stop after 10 items; count the pages fetched.List<T> inside foreach, read the exception, then fix it with RemoveAll.Custom iterators with yield, an async paged iterator, and the common gotchas.
namespace Catalogue;
// The tree's structure stays private; callers just foreach
public sealed class Category(string name)
{
private readonly List<Category> _children = [];
public string Name { get; } = name;
public Category Add(Category child) { _children.Add(child); return this; }
// Depth-first traversal with an explicit stack (no recursion depth limit)
public IEnumerable<Category> DescendantsAndSelf()
{
var stack = new Stack<Category>();
stack.Push(this);
while (stack.Count > 0)
{
var current = stack.Pop();
yield return current; // pauses here until the caller asks for more
for (int i = current._children.Count - 1; i >= 0; i--) // push in reverse to visit in order
stack.Push(current._children[i]);
}
}
}
// var root = new Category("All").Add(new Category("Kitchen").Add(new Category("Kettles"))).Add(new Category("Garden"));
// foreach (var c in root.DescendantsAndSelf()) Console.WriteLine(c.Name); // All, Kitchen, Kettles, Garden
namespace Catalogue;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
public sealed record ProductDto(int Id, string Name, decimal Price);
public sealed record Page<T>(IReadOnlyList<T> Items, string? NextLink);
// Async iterator: fetches the next page only when the caller needs more items
public sealed class ProductApiClient(HttpClient http)
{
public async IAsyncEnumerable<ProductDto> GetAllAsync([EnumeratorCancellation] CancellationToken ct = default)
{
string? next = "products?page=1";
while (next is not null)
{
var page = await http.GetFromJsonAsync<Page<ProductDto>>(next, ct)
?? throw new InvalidOperationException("Empty response");
foreach (var item in page.Items)
yield return item;
next = page.NextLink;
}
}
}
// Caller (.NET 10: LINQ over IAsyncEnumerable is built in)
// await foreach (var p in client.GetAllAsync().Where(p => p.Price > 100m).Take(10).WithCancellation(ct))
// Console.WriteLine(p.Name); // stops fetching pages once 10 items are found
namespace Catalogue;
public static class IteratorGotchas
{
public static void Demo()
{
List<int> numbers = [1, 2, 3];
// 1. Deferred: the filter runs when enumerated, so it sees the later Add
IEnumerable<int> big = numbers.Where(n => n > 1);
numbers.Add(4);
Console.WriteLine(string.Join(",", big)); // 2,3,4
// 2. Multiple enumeration: the work happens twice
IEnumerable<int> slow = numbers.Select(n => { Console.WriteLine($"computing {n}"); return n * 2; });
var count = slow.Count(); // computes 4 items
var first = slow.First(); // computes again
var once = slow.ToList(); // materialise once if you need it more than once
// 3. Modifying while iterating throws
// foreach (var n in numbers) if (n % 2 == 0) numbers.Remove(n); // InvalidOperationException
numbers.RemoveAll(n => n % 2 == 0); // safe alternative
}
}
Count(), then foreach, then Any()). Why it is wrong: The underlying work, such as API calls or queries, runs each time. Instead: Materialise once with ToList() when you need multiple passes.List<T> inside foreach over it. Why it is wrong: The enumerator detects the version change and throws InvalidOperationException. Instead: Iterate a copy, collect changes and apply after, or use RemoveAll.DbContext or stream and enumerating it after the scope is disposed. Why it is wrong: The resource is gone when the iterator finally runs, giving ObjectDisposedException. Instead: Enumerate inside the scope, or return a materialised list.yield method to run at the call. Why it is wrong: The whole body, including checks, runs on the first MoveNext. Instead: Validate in a non-iterator wrapper and call a local iterator function.[EnumeratorCancellation] on an async iterator's token parameter. Why it is wrong: WithCancellation(token) at the call site doesn't reach the iterator, so it can't be cancelled. Instead: Annotate the parameter.List<T> field as a public property. Why it is wrong: Callers can modify the collection and bypass the object's rules. Instead: Expose IEnumerable<T> or IReadOnlyList<T>.yield for a tiny fixed collection that's enumerated in a hot loop. Why it is wrong: Each call allocates an iterator object. Instead: Return an array or a cached IReadOnlyList<T>.The Iterator pattern is so built into C# that the interesting decisions are about laziness and ownership: should this method stream or materialise, and who controls the resources the iterator holds? Streaming is right for large or unbounded sources and pipelines; materialising is right when callers need multiple passes, counts or a stable snapshot.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Return IEnumerable<T> via yield |
Large or lazy sequences, custom traversals | Deferred work, re-runs per enumeration | Callers need counts or multiple passes |
Return IReadOnlyList<T> |
Data already in memory, multiple passes | Memory for the whole list | Huge or unbounded data |
IAsyncEnumerable<T> |
Paged APIs, database streaming, server-sent results | Async state machine per item batch | Small results fetched in one call |
List<T>.ForEach / callbacks |
Fire a side effect per item | Can't stop early or compose with LINQ | Anything you'd want to filter or page |
A method that uses yield return is an iterator, and the compiler rewrites it into a state machine class that implements IEnumerable<T> and IEnumerator<T>. Locals become fields, a state field remembers where it paused, and each MoveNext runs to the next yield return. yield break ends the sequence. Execution is lazy, and finally and using blocks run when iteration finishes or the consumer disposes early. Iterators can't have ref or out parameters or yield inside a catch, and async iterators add await. They're ideal for streaming and large or infinite sequences.
Deferred execution means a LINQ query is a recipe that runs each time you enumerate it, not when you write it. That explains all four symptoms. The "changing" list is a query that re-reads its source and captured variables. The ObjectDisposedException comes from enumerating an EF query after the DbContext was disposed. Three log lines are three enumerations, and the late exception is a lambda failing during enumeration. I fix them by materialising once with ToList at a clear boundary inside the context's scope, and by turning on CA1851 for multiple enumeration.
IEnumerable<T> is just a promise that you can get an enumerator. IEnumerator<T> gives MoveNext, Current and Dispose, and that is all: no count, no indexing, and possibly lazy, infinite or single-use. foreach is pattern-based and compiles to a while (MoveNext()) loop with Dispose in a finally. List<T> uses a struct enumerator, which gets boxed if you iterate through the interface. IAsyncEnumerable<T> is the async version, used with await foreach. I accept IEnumerable<T> when I only iterate once, and return IReadOnlyList<T> unless I mean to stream.
Last updated 18 Nov 2026.