A Peak at Iterators
Now that you’ve learned about iteration constructs in general and the
foreach loop’s capability to deal with
IEnumerable objects, we’re in an ideal position to introduce the concept of iterators. So far, all enumeration sources we’ve seen are collections of some sort. But what about creating our own sources to provide sequences of data consumable through enumeration?
Observe the true nature of the
foreach loop first. In its true essence, it pulls data from some sequence of elements by querying that sequence using the
Current members. Nothing requires the data returned to be available before the iteration starts; what about computing it as we go? Here we enter the domain of lazy evaluation.
An example of a lazy ...