As a precursor to the LINQ feature set, C# 2.0 introduced the concept of iterators to make the definition of IEnumerable<T> and IEnumerator<T> objects easier. You’ve seen before how powerful custom implementations of those interfaces can be (for example, to yield a sequence of numbers to a consumer, in an on-demand basis). All you need to do is respond properly to MoveNext method and Current property getter calls.

Conceptually though, your task is even simpler: You just want to hand out objects to a consumer when asked to do so. This feels quite a bit like returning data from a method, the difference being you don’t just return a single object but a sequence of objects, one at a time.

Iterators precisely enable you to do this, using ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.