Chapter 6. Iterators, Partial Types, and Partial Methods

6.0. Introduction

Iterators allow for a block of code to yield an ordered sequence of values.

Iterators are a mechanism for producing data that can be iterated over by the foreach loop construct. However, iterators are much more flexible than this. You can easily generate a sequence of data returned by the enumerator (lazy computation); it does not have to be hardcoded up front (eager computation). For example, you could easily write an enumerator that generates the Fibonacci sequence on demand. Another flexible feature of iterators is that you do not have to set a limit on the number of values returned by the iterator, so in this example, you could choose when to stop producing the Fibonacci sequence. This is an interesting distinction in the LINQ world. Iterators like the one produced by the IEnumerable version of Where are lazy, but grouping or sorting requires eagerness.

Iterators allow you to hand the work of writing this class off to the C# compiler. Now, you need to add only an iterator to your type. An iterator is a member within your type (e.g., a method, an operator overload, or the get accessor of a property) that returns either a System.Collections.IEnumerator, a System.Collections.Generic.IEnumerator<T>,a System.Collections.IEnumerable,or a System.Collections.Generic.IEnumerable<T> and that contains at least one yield statement. This allows you to write types that can be used by foreach loops.

Iterators play an important ...

Get C# 3.0 Cookbook, 3rd Edition 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.