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 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.