Search for a command to run...

Some data arrives all at once. Some arrives one piece at a time, and you never know how much of it there is. A list of orders in memory, rows streaming out of a database, lines in a log file, pages from an API - from the consumer's side, all four are the same question: give me the next item, and tell me when there are no more. The Iterator pattern is the answer to that question, and in .NET it is not a pattern you reach for - it is the shape of the language itself. Every foreach loop, every LINQ operator, every streaming read is an iterator, and most of them were written by the compiler, not by you.
The Gang of Four definition is short: provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Two ideas in one sentence. Sequential access - one item at a time, in order, without skipping or going back. And no exposure - the consumer never learns whether the items live in an array, a database cursor, or a paginated API. The pattern is a boundary between 'give me the next one' and 'how the next one is produced'. The Observer post in this series was the push twin of the same idea: there, the provider shouts; here, the consumer asks. Same grammar, direction reversed.
Make it concrete. The store needs a nightly export of every order ever placed - for the accountant, for a report, for a migration. The naive version loads them all into a List<Order> and loops. It works at a thousand orders. At a million, the list itself is the problem: memory, garbage collection, a query that has to finish before the first row is written. What the exporter actually needs is one order at a time, in order, while the database hands them over. It does not need a list. It needs a cursor - something that answers 'is there another one?' and 'what is it?' and nothing else. That cursor is the Iterator pattern, and .NET has it as two interfaces.
IEnumerable<T> is the sequence. It has exactly one method: GetEnumerator(). That is all it promises - 'I can hand you a cursor'. It promises no Count, no indexer, no Add. The enumerator is IEnumerator<T>: MoveNext() advances and returns false at the end, Current reads the item at the cursor, and Dispose() releases whatever the walk held on to. The enumerator starts positioned before the first element - Current is undefined until the first MoveNext() call, a detail the documentation states plainly and code forgets constantly. And the two are separate objects on purpose: one sequence can hand out many independent cursors, which is why two nested foreach loops over the same list never interfere.
And foreach is not a primitive over lists. It is sugar for exactly this loop:
Three facts fall out of that desugaring. First, foreach never asks 'how many are there' and never asks for item seven - only 'is there another one' and 'what is it'. Second, the enumerator is always disposed, even when the loop body throws or breaks early - which is why enumerators can safely hold database cursors and file handles. Third, foreach is pattern-based: the compiler looks for a GetEnumerator method with the right shape, and a type can support foreach without ever implementing IEnumerable<T>. Arrays, Span<T>, and List<T>'s struct enumerator all ride on this - iterating a list allocates nothing, because its enumerator is a struct, not a class.
Before yield return, the shape by hand. An order catalog with a cursor that carries its own state. The state field is the whole lesson: an enumerator is a state machine with a memory of where it stopped.
Every part of this class is doing one job. _index is the state - the memory of where the walk stopped. MoveNext moves it and reports whether there is more. Current reads it. Dispose releases nothing here, but it is the hook for the day the source is a database cursor. And Reset throws, deliberately: it exists for COM interop - the documentation says so - and no modern code should call it. A fresh enumerator is the reset. Write this class once and yield return stops being magic: it is the compiler writing this class for you, _index and all.
Six lines replace the class above. The filtering version, and an infinite one to prove the point about laziness:
Two rules define an iterator method, and everything else follows. Rule one: calling it runs none of its body. ExpensiveOrders(orders, 1000) returns immediately - no loop, no filter, nothing. The body runs only as items are requested, one MoveNext at a time, and it pauses at each yield return and resumes exactly where it stopped. Rule two: that pause is the state machine - the compiler generates a class implementing IEnumerator<T> with a state field, and your locals become its fields. That is also why the body re-runs on every enumeration: a second foreach over the same IEnumerable<Order> starts the method from the top. Infinite sequences work for the same reason - OrderNumbers never ends, and the consumer decides when to stop with Take(10) or break. Streaming is not a feature you add; it is what you get when the producer only runs when asked.
This is where the series pays off. Every LINQ operator is an iterator method wearing an extension-method coat. Where is a loop with an if and a yield return; Select is a loop with a yield return of the projection; Take is a loop with a counter and a yield break. That is why LINQ is lazy: a query is a chain of iterators, and nothing in the chain runs until something pulls - a foreach, a ToList, a Count. The chain is also why a query over a file bigger than RAM works: Where reads a line, decides, and either yields it or drops it; no intermediate list ever exists.
And the trap is the same mechanism. expensive is not a result - it is a recipe. Count() runs the recipe once; the foreach runs it again. If the recipe hits a database or an API, you just paid twice, and if the data changed between the two passes, the count and the loop disagree. The fix is materialisation - ToList() once, then count and loop over the list - or simply never enumerate a lazy sequence twice when the work behind it is expensive. Deferred execution is a feature; re-running expensive work by accident is the price of forgetting it.
The same pattern, one await later. When getting the next item is itself asynchronous - a database row, a page from an API, a message from a queue - the synchronous cursor blocks a thread while it waits. C# 8 added the async twin: IAsyncEnumerable<T> with GetAsyncEnumerator, and IAsyncEnumerator<T> whose MoveNextAsync returns ValueTask<bool>. The consumer spells it await foreach, and the compiler desugars it into the same loop with awaits and a DisposeAsync in the finally.
Two details. The [EnumeratorCancellation] attribute wires the caller's token into the iterator - without it, the token passed to GetAsyncEnumerator is ignored and cancellation silently does nothing. And the ValueTask<bool> is deliberate: when the next item is already available, MoveNextAsync allocates nothing. The async twin is also the shape EF Core uses to stream rows without loading the table - AsAsyncEnumerable turns a query into a stream, and the rows arrive one at a time while the export writes them. The same pull grammar, with waiting allowed between items.
The costs are the usual price of laziness:
Multiple enumeration re-runs the work. Every foreach over the same lazy sequence starts the iterator from the top - a database hit, an API call, a file read, all over again.
Deferred exceptions. An argument check inside an iterator does not throw when the method is called - it throws on the first MoveNext. Validate arguments in a wrapper method and return a local iterator function, so bad input fails fast.
Mutating during enumeration. Most collections version-check their enumerators and throw InvalidOperationException - 'Collection was modified' - the moment the source changes mid-loop. The cursor is a snapshot of position, not of data.
IEnumerable escaping its context. Returning IEnumerable<T> from a repository while the DbContext is disposed means the query runs after disposal - ObjectDisposedException at enumeration time, far from the code that caused it. Materialise, or return IAsyncEnumerable<T> and keep the lifetime explicit.
One-pass cursors. An enumerator moves forward only. If you need a count, an index, or a second pass, you need a List, not an iterator - and the return type should say so.
So when do you skip it? When the consumer needs the count, an index, or a second pass - return a List<T> or an array and say so in the type. When the sequence is tiny and already in memory - a list is simpler and honest. When the work behind each item is expensive and the caller will enumerate twice - materialise once, at the boundary. The iterator is for one-pass, pull-driven consumption. If the consumption is not one-pass, the pattern is the wrong shape, and the type should say so.
There is one check that settles whether the pattern is doing its job in your code: swap the source without touching the consumer. The exporter loops over IEnumerable<Order>. Today the source is a list in memory; tomorrow it is a database cursor; next month it is pages from an API. If the exporter's file stays closed through all three swaps, the boundary is real. If every new source means editing the consumer, you have a loop over a list wearing a pattern's name.
Swap the source without touching the consumer. If you can, the pattern is doing its job.
Start with yield return. It is the form you will use most, and it costs one keyword. Reach for a hand-built enumerator when the state machine needs to be visible - a cursor over pages, a custom traversal, a stream with cleanup. Reach for IAsyncEnumerable<T> when the next item needs an await. And the next time a method returns a list that was built only to be looped over once, remember the flip: stop building the list. Let the consumer pull. The next post in the series goes inside LINQ itself: the operators are iterators, and now that you have built one, their deferred execution stops being a fact to memorise and becomes a mechanism you can trace.
A list of orders in memory, rows streaming out of a database, pages from an API - from the consumer's side they are the same question: give me the next item, and tell me when there are no more. The Iterator pattern is that question answered as an interface pair, and in .NET it is the shape of foreach and LINQ themselves: hand-built enumerators, yield return, deferred execution, and the async twin IAsyncEnumerable<T> - including the costs, and when a List is the honest answer.
An order is placed, and five parts of the system need to know. The Observer pattern flips who knows about whom: the publisher announces one fact, subscribers come and go, and the publisher never changes. From hand-built subjects to C# events, IObservable<T>, and MediatR notifications - with the push and pull models demonstrated in code - including the costs, and when a direct call is the honest answer.
A price is not a decimal, a phone number is not a string, and an email is not a string either. Primitive obsession is the habit of modelling domain concepts with the language's built-in types — and value objects are the small, boring, enormously effective fix.