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).
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();
}
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.
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."