SOLID & Design Patterns Interview Question #44
What is the Iterator Pattern?
Structural, Creational & Behavioral Patterns Mid-Level Intermediate
Quick Interview Answer
The Iterator Pattern provides a way to traverse elements of a collection without exposing the collection's internal representation. The caller works through a traversal abstraction instead of managing storage details.
Detailed Explanation
The Iterator Pattern provides a way to traverse elements of a collection without exposing the collection's internal representation. The caller works through a traversal abstraction instead of managing storage details.
C# implements this concept through IEnumerable<T>, IEnumerator<T>, foreach, and iterator methods using yield return.
Code Example
public IEnumerable<int> EvenNumbers(
IEnumerable<int> source)
{
foreach (var number in source)
if (number % 2 == 0)
yield return number;
}