Information Technology Reference
In-Depth Information
More about Iterators
Some other important things to know about iterators are the following:
Iterators require the
System.Collections.Generic
namespace, so you should include it
with a
using
directive.
In the compiler-generated enumerators, the
Reset
method is not supported. It is
implemented, since it is required by the interface, but the implementation throws a
System.NotSupportedException
exception if it is called. Notice that the
Reset
method is
shown grayed out in Figure 20-8.
Behind the scenes, the enumerator class generated by the compiler is a state machine with
four states:
Before
: The initial state before the first call to
MoveNext
.
Running
: The state entered when
MoveNext
is called. While in this state, the enumerator
determines and sets the position for the next item. It exits the state when it encounters a
yield return
, a
yield break
, or the end of the iterator body.
Suspended
: The state where the state machine is waiting for the next call to
MoveNext
.
After
: The state where there are no more items to enumerate.
If the state machine is in either the
before
or
suspended
states, and there is a call to the
MoveNext
method, it goes into the
running
state. In the running state, it determines the next
item in the collection, and sets the position.
If there are more items, the state machine goes into the
suspended
state. If there are no
more items, it goes into the
after
state, where it remains. Figure 20-9 shows the state machine.
Figure 20-9.
An iterator state machine