Posted on Friday January 23, 2009

C# Design Patterns: the Iterator pattern

Summary

Iterate through a list of items, with an enumerator class ordering the set/list before it is iterated through.

Example

Iterators are built into C# via foreach statements and IEnumerator. The iterator is the foreach statement, which requires the object it is iterating through to implement IEnumerator. The foreach statement calls GetEnumerator on the collection or class you specify. With the introduction of the yield keyword into C# this has been made even simpler.

The output is:

Andrew
(Gemini)
Berfa
(Cancer)
Fred
(Aquarius)
Hans
(Pisces)
Zach
(Scorpio)