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:

public static IEnumerable<T> StartWith<T>(this IEnumerable<T> tail, T head) {    yield return head;    foreach (T item in tail)        yield return item;}

This operator enables you to prepend an ...

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.