Listing 6.1 Code using the (as yet unimplemented) new collection type
Listing 6.2 Skeleton of the new collection type, with no iterator implementation
164 CHAPTER 6 Implementing iterators the easy way
Instead, let??™s create another class to implement the iterator itself. We??™ll use the fact
that in C# a nested type has access to its enclosing type??™s private members, which
means we can just store a reference to the ???parent??? IterationSample, along with the
state of how far we??™ve gone so far. This is shown in listing 6.3.
class IterationSampleIterator : IEnumerator
{
IterationSample parent;
int position;
internal IterationSampleIterator(IterationSample parent)
{
this.parent = parent;
position = -1;
}
public bool MoveNext()
{
if (position != parent.values.Length)
{
position++;
}
return position < parent.values.Length;
}
public object Current
{
get
{
if (position==-1 ||
position==parent.values.Length)
{
throw new InvalidOperationException();
}
int index = (position+parent.startingPoint);
index = index % parent.values.Length;
return parent.values[index];
}
}
public void Reset()
{
position = -1;
}
}
What a lot of code to perform such a simple task! We remember the original collection
of values we??™re iterating over B and keep track of where we would be in a simple
zero-based array C. To return an element we offset that index by the starting
point G.
Pages:
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332