In keeping with the interface, we consider our iterator to start logically
before the first element D, so the client will have to call MoveNext before using the
Current property for the first time. The conditional increment at E makes the test
Listing 6.3 Nested class implementing the collection??™s iterator
B Refers to
collection we??™re
iterating over
C
Indicates
how far we??™ve
iterated
D
Starts before
first element
E Increments
position if we??™re
still going
Prevents access before
first or after last element
F
Implements
wraparound
G
Moves back to
before first element
H
165 C# 2: simple iterators with yield statements
at F simple and correct even if MoveNext is called again after it??™s first reported that
there??™s no more data available. To reset the iterator, we set our logical position back
to ???before the first element??? H.
Most of the logic involved is fairly straightforward, although there??™s lots of room
for off-by-one errors; indeed, my first implementation failed its unit tests for precisely
that reason. The good news is that it works, and that we only need to implement
IEnumerable in IterationSample to complete the example:
public IEnumerator GetEnumerator()
{
return new IterationSampleIterator(this);
}
I won??™t reproduce the combined code here, but it??™s available on the book??™s website,
including listing 6.
Pages:
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333