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 MoveNext and 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access