I am learning the design patterns, and I found Iterator. Do we still need to use it?
Since we have collection, I am confused why we still need the Iterator Design Pattern.
Iterator pattern is useful when you want to provide a standard way to iterate over a collection and hide the implementation logic from client program. The logic for iteration is embedded in the collection itself and it helps client program to iterate over them easily.
Iterator Pattern: AdvantagesThe code is easier to use, understand and test since the iterator uses the Single Responsibility and Open/Closed SOLID principles. The Single Responsibility Principle allows us to clean up the client and collections of the traversal algorithms.
The Iterator design pattern allows us to separate out all the logic for iterating over a collection. There are different collection objects and all of them need their own iterator. The reason is each collection has its own structure.
The main idea of the Iterator pattern is to extract the traversal behavior of a collection into a separate object called an iterator. Iterators implement various traversal algorithms. Several iterator objects can traverse the same collection at the same time.
IEnumerator<T>
is an iterator and IEnumerable<T>
creates them. Almost all collections implement IEnumerable<T>
.
It's at the heart of Linq-To-Objects which is one of the core features of C# 3. So iterators are very important in modern C#.
C# 3 also introduced a special language feature allowing you to easily implement an iterator using the yield return
syntax.
foreach
is based on iterators too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With