The IEnumerator interface of C# is usually fine for visiting a collection of elements. However, often times when I’m doing something more complicated I want to split up the functionality of MoveNext1. In this post I’ll define a new interface and show how to employ the Adapter pattern to implement it.
MoveNext does two things: 1) it moves the cursor forward one position and 2) returns a bool value that indicates if there is an element at the current position. There are occasions where I want that boolean persisted. This requires me to keep a local variable (or a member variable) to maintain this piece of information. I’ve done this enough times that I decided that the iterator should store this for me. So I defined the interface IIterator.
The MoveNext method now has no return value. It simply moves to the next element. You must separately inspect HasCurrent property to see if there is an element at the current posistion.
None of the collection classes implement this interface. However, it it trivial to write an adapter class that implements and can wrap an IEnumerator.
The constructor is hidden because otherwise we could be given an enumerator that is not at the beginning of the collection. To ensure we get a “fresh” enumerator I only provide a GetIterator method which takes an IEnumerable from which I can request a new IEnumerator.
This already allows us to retrieve an iterator but we can provide a little syntactic sugar by use of an extension method.
And now we can request an iterator for an enumerable object as shown in the next trivial example.
Unfortunately, I have not found an example of where I’ve used this. I’ll keep looking. ↩