Information Technology Reference
In-Depth Information
Iterator Blocks
A code block with one or more
yield
statements is an
iterator block
. Any of the following three
types of code blocks can be iterator blocks:
A method body
An accessor body
An operator body
Iterator blocks are treated differently than other blocks. Other blocks contain sequences of
statements that are treated
imperatively
. That is, the first statement in the block is executed,
followed by the subsequent statements, and eventually control leaves the block.
An iterator block, on the other hand, is not a sequence of imperative commands to be
executed at one time. Instead, it describes the behavior of an enumerator class that you want
the compiler to build for you. The code in the iterator block describes how to enumerate the
elements.
Iterator blocks have two special statements:
The
yield return
statement specifies the next item in the sequence to return.
The
yield break
statement specifies that there are no more items in the sequence.
The compiler takes this description of how to enumerate the items and uses it to build the
enumerator class, including all the required method and property implementations. The
resulting class is nested inside the class where the iterator is declared. Figure 20-8 shows the
code on the left and the resulting objects on the right. Notice how much is built for you auto-
matically by the compiler.
Figure 20-8.
An iterator that produces an enumerator