Tutorials Design Patterns Mastery

Iterator Pattern: Unified traversal of collections

On this page

The Iterator Pattern

The Iterator Pattern provides a way to access the elements of an aggregate object (like a List or Tree) sequentially without exposing its underlying internal structure (like nodes, pointers, or indices).

1. Real-World .NET Example: IEnumerable

In C#, almost every collection implements IEnumerable. This is the Iterator pattern in its purest form. You don't need to know if the data is in an Array, a LinkedList, or a Database; you just call foreach.

public interface IIterator 
{
    bool HasNext();
    object Next();
}

2. Encapsulation

The biggest benefit is **Encapsulation**. If you change your internal storage from a Dictionary to a List, you only update the Iterator. All your UI code and business logic that uses foreach remains 100% unchanged.

4. Interview Mastery

Q: "Why does C# use an Enumerator state machine instead of a simple integer index for iterating?"

Architect Answer: "Because not all collections are indexable. A binary tree or a linked list doesn't have an 'Index 5'. By using an Enumerator object that tracks its own internal state, .NET can provide a unified way to loop over any data shape. It also allows for **Deferred Execution** (Linq), where the data is only calculated the moment the iterator moves forward, saving massive amounts of memory."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details