IEnumerator is implemented by classes that support simple iteration over a collection. By simple, I mean that you can only move forward from element to element, although you can go back to the start at any time.

Enumerators are read-only because the object takes a snapshot of the collection when it is created. This means that it is perfectly possible to have more than one enumerator with access to the same collection. The underlying collection must not be changed while an enumerator is active because its snapshot would then be out of date. If this happens, the iterator will throw exceptions whenever you try to use it.

The Enumerator interface has three members. The MoveNext() method advances the iterator to the next element in the collection. Note that the initial position of the iterator is before the first element in the collection, so you need to call MoveNext() once in order to advance to the first element.

The function returns a Boolean value, which will be true if the iterator successfully advanced to the next element, and false once it has passed the end. The Reset() method can be used to set the iterator back to its initial position, that is, before the first element in the collection.

The Current property returns a reference to the current object in the collection. This property will throw an invalid operation exception under two circumstances:

■ If the enumerator is positioned before the start or after the end of the collection

■ If the collection has been modified since the enumerator object was created

See the Immediate Solutions section for examples of enumerator usage.

0 0

Post a comment