Iterator Pattern
Traverse a collection without exposing its representation, using a separate object for traversal state.
· Last updated: 2026-11-07 · 11 min read
Overview
If the code that reads a playlist in order indexes straight into the internal array, then changing how the playlist stores its items means changing the caller too. The reading side ends up carrying the array's length and its indexing rules. Keeping what is stored separate from how far it has been read lets the traversal method stay hidden.
That hidden traversal is the Iterator's job. It advances to the next item and exposes the current one. The collection holds the items; each iterator has its own position.
UML
Playlist is what creates the iterator. Callers only ever use two members of IEnumerator<string>, MoveNext() and Current. How the playlist stores its items stays hidden behind them. The yield return in the example is what the C# compiler expands into the iterator implementation.
History
GoF cataloged Iterator as a behavioral pattern in Design Patterns in 1994. It provides sequential access without exposing the aggregate representation.1
Inspired by Alphard's generators, Russ Atkinson of the CLU team designed the language's yield iterator in 1975, giving the language a control structure for yielding the elements of an abstract collection one at a time.23 Alexander Stepanov's C++ STL (1994) later generalized iterators to decouple generic algorithms from containers, while C# 2.0 (2005) and ECMAScript 2015 revived CLU's yield by compiling generator functions into state-machine iterators automatically.
Why use it?
Splitting storage from reading leaves the calling side with less to know. Callers read the items in order without ever receiving the internal array, and even when the same playlist is read in several places, each iterator keeps its own position.
What happens while the iterator runs is a separate question. When traversal is deferred, I/O can occur during the loop, and it can fail there as well. Even so, this example reads only a string array copied when the playlist was created, and it makes no guarantee about a list that is being modified or about a remote stream.
Example
Enumerate Playlist with foreach without exposing its array.
using System;
using System.Collections.Generic;
using System.Linq;
var playlist = new Playlist(new[] { "intro", "outro" });
foreach (string track in playlist) Console.WriteLine(track);
// Hide the internal array and expose only the traversal protocol.
sealed class Playlist : IEnumerable<string>
{
private readonly string[] tracks;
public Playlist(IEnumerable<string> tracks) => this.tracks = tracks.ToArray();
// Each call returns a generator with its own traversal position.
public IEnumerator<string> GetEnumerator()
{
foreach (string track in tracks) yield return track;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
intro
outroforeach relies on the iterator protocol, and yield return is the C# syntax that lets you write an implementation of that protocol concisely. The compiler writes those members for you.
An extended example
This time, take two iterators from the same playlist and advance them at different rates.
using System;
using System.Collections.Generic;
using System.Linq;
var playlist = new Playlist(new[] { "intro", "outro" });
using var first = playlist.GetEnumerator();
using var second = playlist.GetEnumerator();
if (first.MoveNext()) Console.WriteLine("first: " + first.Current);
if (second.MoveNext()) Console.WriteLine("second: " + second.Current);
if (first.MoveNext()) Console.WriteLine("first: " + first.Current);
Console.WriteLine("first has next: " + first.MoveNext());
Console.WriteLine("second: " + second.Current);
// Hide the internal array and expose only the traversal protocol.
sealed class Playlist : IEnumerable<string>
{
private readonly string[] tracks;
public Playlist(IEnumerable<string> tracks) => this.tracks = tracks.ToArray();
// Each call returns a generator with its own traversal position.
public IEnumerator<string> GetEnumerator()
{
foreach (string track in tracks) yield return track;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
first: intro
second: intro
first: outro
first has next: False
second: introEach iterator keeps its own place. Even if you push the first iterator one step further, the second iterator's Current value stays the same, and once MoveNext() has returned false, Current is not read.
TypeScript example
Here is the same separation in TypeScript. Playlist is the one holding the items, and an iterator created when traversal starts carries its current position with it. Because the position lives with the iterator rather than in one shared collection, two traversals do not disturb each other's progress.
// Hide the internal array and expose only the traversal protocol.
class Playlist implements Iterable<string> {
private readonly tracks: readonly string[];
constructor(tracks: readonly string[]) { this.tracks = [...tracks]; }
// Each call returns a generator with its own traversal position.
*[Symbol.iterator](): Generator<string, void, unknown> {
for (const track of this.tracks) yield track;
}
}
function step(iterator: Iterator<string>): string {
const result = iterator.next();
return result.done ? "(end)" : result.value;
}
const playlist = new Playlist(["intro", "outro"]);
const first = playlist[Symbol.iterator]();
const second = playlist[Symbol.iterator]();
console.log("first: " + step(first));
console.log("first: " + step(first));
console.log("second: " + step(second));
console.log("second: " + step(second));first: intro
first: outro
second: intro
second: outroIn TypeScript, Symbol.iterator takes over the job that GetEnumerator() does in C#. A generator function produces a separate, fresh iterator on every call, and once traversal has finished you check the done value that next() returns. Only the shape of the call site changes; the division of roles stays the same.
Use LINQ when querying and transforming are all you need
If all you need is to pick some items out of a collection you can already traverse and transform them, there is no reason to write another iterator class. In C# LINQ, Where takes the predicate that selects and Select takes the transformation function, and together they compose the traversal. The code below uppercases only the track names that begin with in, and it leaves the input array alone.
C#
using System;
using System.Linq;
var tracks = new[] { "intro", "outro", "interlude" };
// Where filters, Select transforms, and ToArray enumerates and stores the results now.
string[] labels = tracks
.Where(track => track.StartsWith("in", StringComparison.Ordinal))
.Select(track => track.ToUpperInvariant())
.ToArray();
Console.WriteLine(string.Join(",", labels));
Console.WriteLine(string.Join(",", tracks));TypeScript
const tracks = ["intro", "outro", "interlude"];
// Array filter and map evaluate immediately and return new arrays.
const labels = tracks
.filter(track => track.startsWith("in"))
.map(track => track.toUpperCase());
console.log(labels.join(","));
console.log(tracks.join(","));INTRO,INTERLUDE
intro,outro,interludeProducing the same result is not the same as running the same way. These examples work with strings in memory. LINQ Where and Select run when the result is actually enumerated, and ToArray decides when that moment comes, whereas TypeScript array filter and map evaluate immediately. For the ASCII track names used here, both sides pick the same items, uppercase them, and leave the input untouched. Even so, using a functional style does not by itself remove external calls or shared-state mutation.
Microsoft: Introduction to LINQ queries
Keeping the element type with Iterator<T>
Using T for the element type lets the same traversal structure work for strings and numbers. IEnumerator<T> in C# and Iterator<T> in TypeScript express that contract. Each call to Aggregate<T>.CreateIterator() creates independent traversal state. String or number, the caller works with the same members.
C# callers read Current when MoveNext() returns true; TypeScript callers read value when next().done is false. Empty strings and zero are valid elements, so the element’s truthiness cannot indicate the end of traversal. That test holds when the element type widens to T.
C#
using System;
using System.Collections.Generic;
using System.Linq;
var aggregate = new Aggregate<string>(new[] { "a", "b" });
using var first = aggregate.CreateIterator();
using var second = aggregate.CreateIterator();
first.MoveNext();
first.MoveNext();
second.MoveNext();
Console.WriteLine(first.Current);
Console.WriteLine(second.Current);
// TYPES
sealed class Aggregate<T>
{
private readonly T[] values;
public Aggregate(IEnumerable<T> values) { this.values = values.ToArray(); }
// Each iterator has its own position over the same element array.
public IEnumerator<T> CreateIterator() => ((IEnumerable<T>)values).GetEnumerator();
}b
aTypeScript
class Aggregate<T> {
readonly #values: T[];
constructor(values: readonly T[]) { this.#values = [...values]; }
// Preserve T while putting the position in a fresh iterator.
createIterator(): Iterator<T, undefined> { return this.#values[Symbol.iterator](); }
}
const aggregate = new Aggregate<string>(["a", "b"]);
const first = aggregate.createIterator();
const second = aggregate.createIterator();
first.next();
const a = first.next();
const b = second.next();
if (!a.done) console.log(a.value);
if (!b.done) console.log(b.value);b
aAggregate copies the input array when constructed. Later changes to the original array do not alter its element sequence, but mutable objects stored as elements are still shared. The copy stops at the array itself.
The official references describe the type-parameter syntax and library contracts.4
External vs. internal iterators, fail-fast checks, and disposal
GoF drew a sharp line between external iterators and internal iterators. With an external (pull) iterator such as C#'s MoveNext() or JavaScript's next(), the caller advances the cursor step by step, making it easy to zip two sequences in lockstep or pause mid-stream. With an internal (push) iterator such as forEach or a Fold, the collection drives the loop itself: call sites shrink to a single callback, but interleaving two traversals becomes awkward.
Two runtime subtleties matter in production: concurrent modification and resource cleanup on early exit. Standard collections like .NET's List<T> maintain an internal version counter so that mutating the list during enumeration causes the very next MoveNext() call to throw InvalidOperationException (fail-fast) rather than silently skipping or repeating items. Moreover, because C#'s foreach compiles to a try / finally block that calls IDisposable.Dispose() on the enumerator, any code that calls GetEnumerator() manually must wrap the enumerator in a using statement—otherwise breaking out of a yield return generator early will never run its finally cleanup block.
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Behavioral patterns, Iterator. ↩
- Barbara Liskov, Alan Snyder, Russell Atkinson, and Craig Schaffert, "Abstraction Mechanisms in CLU," Communications of the ACM 20(8), 1977, pp. 564–576. DOI. ↩
- Barbara Liskov, A History of CLU, MIT-LCS-TR-561, 1992, §3.10, p.16. Alphard influence and Atkinson's September 1975 design note. Author's account. ↩
- C# generics; TypeScript generics; IEnumerator<T>; TypeScript iterators ↩