The iterator pattern provides a client with a way to access the elements of an aggregate object sequentially without having to know the underlying representation. The iterator is especially useful because it provides the client with a common interface so it doesn’t need to know anything about the underlying data structure.

image

If you want to loop through an collection of elements, the iterator pattern comes in very handy. In this example the client first fills an aggregate object with string elements. Next, an iterator is instantiated with the collection. Last, the iteration is done. The fun part is that you can change the implementations of underlying data and iterator without having to change the client.

The abstract aggregate class its most important abstract method is CreateIterator. For convenience of this example, an indexer and a property Count are also defined. The concrete aggregate object is just a wrapper around an ordinary ArrayList.

The iterator does the looping work. First, an aggregate object is injected into the iterator upon instantiation. The rest of the code is just implementation of all abstract members.

Knowing this, can you imagine a real world situation when to use this pattern? This is such an important pattern, that it is a built-in pattern in C#. If you want read more about use of this pattern, read Using the Iterator Pattern in C# ASP .NET, by Kory Becker

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.