wikipedia.org/wiki/Sequence_diagram if this is unfamiliar to you.
Listing 6.5 Showing the sequence of calls between an iterator and its caller
168 CHAPTER 6 Implementing iterators the easy way
Console.WriteLine ("Starting to iterate");
while (true)
{
Console.WriteLine ("Calling MoveNext()...");
bool result = iterator.MoveNext();
Console.WriteLine ("... MoveNext result={0}", result);
if (!result)
{
break;
}
Console.WriteLine ("Fetching Current...");
Console.WriteLine ("... Current result={0}", iterator.Current);
}
Listing 6.5 certainly isn??™t pretty, particularly around the iteration side of things. In
the normal course of events we??™d just use a foreach loop, but to show exactly what??™s
happening when, I had to break the use of the iterator out into little pieces. This
code broadly does what foreach does, although foreach also calls Dispose at the
end, which is important for iterator blocks, as we??™ll see shortly. As you can see,
there??™s no difference in the syntax within the method even though this time we??™re
returning IEnumerable
instead of IEnumerator. Here??™s the output from
listing 6.5:
Starting to iterate
Calling MoveNext()...
Start of GetEnumerator()
About to yield 0
... MoveNext result=True
Fetching Current...
... Current result=0
Calling MoveNext()...
After yield
About to yield 1
... MoveNext result=True
Fetching Current.
Pages:
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339