c# – Why do I need an iterator pattern?


C # courses regularly talk about the iterator pattern. Why is it needed at all if we can send the necessary elements to the collection and work with it? Why do we need custom collections if you can use standard ones?


An iterator is "not a user-defined collection", but a tool for traversing this collection and not only a collection, but in general everything that can be iterated over sequentially according to some algorithm. Collection traversal is just a special case.

The iteration algorithm is hidden inside the iterator, which allows you to have a separate data object itself and many iterators with different traversal algorithms (SRP)

That is, an iterator is a class that encapsulates what kind of data traversal algorithm with a standardized enumerator interface

Scroll to Top