How Iterators Work

To wrap up our exploration of lazy execution related to iterators, let’s briefly look at how the compiler realizes iterators. We already know an iterator is a syntactical way to implement IEnumerable<T> or IEnumerator<T> automatically. The key trick is to keep track of the local state of the iterator across different calls to MoveNext.

As an example, consider the following sequence operator, which doesn’t come in LINQ out of the box. Put its definition in a static class to use it on enumerable sequences:

image

This operator enables you to prepend an existing sequence with a single object, much like a cons-cell in LISP does. No worries ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.