About This eBook by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required