
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
323
Chapter 6
CHAPTER 6
Iterators and Partial Types
6.0 Introduction
Two of the four main new features in C# 2.0 are iterators and partial types. Iterators
allow for a block of code to yield an ordered sequence of values. Partial types allow
for different parts of classes to be placed in different locations.
Iterators are a mechanism whereby a class can enumerate data using the
foreach loop
construct. However, iterators are much more flexible than this. You can easily gener-
ate a sequence of data returned by the enumerator; it does not have to be hardcoded
up front. 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.
Previous versions of the .NET Framework required you to perform several steps to
allow the
foreach construct to operate on your type. First, you had to implement the
IEnumerable interface on your type, then you had to implement the IEnumerator
interface on another type. This second type performed the actual work to enable
foreach functionality. The methods MoveNext and Reset, along with the Current prop-
erty, then had to be ...