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

  • If you are given an exhaustive answer, mark it as correct (tick the selected answer). - andreycha

2 answers 2

An iterator is a “non-user collection”, but a tool to bypass this collection and not just the collection, but generally everything that can be sequentially iterated over by some sort of algorithm. Bypassing the collection 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 in itself which data crawl algorithm with a standardized enumerator interface

    The iterator abstracts from you not only the collection itself, but also the state of its crawling. For example, for an array, this is the current index, for structures based on a tree, this is the current node, and so on. Without iterators, you would have to know for each collection exactly how to bypass it and have access to its internal structures (for example, a tree-based sorted set usually does not put its nodes in public access).


    Why do you need custom collections? Very simple: the standard does not always know what you need. For example, if you want to model a one-to-one correspondence (that is, a Dictionary type, but so that you can also quickly find the key by value), you will have to write your collection.