#556 – Using an Enumerator Explicitly

An enumerator is an object that knows how to move through a sequence of elements.  In C#, the foreach statement provides this same functionality wrapping an enumerator.

You can use an enumerator to iterate through a collection, rather than a foreach statement.  This helps in understanding how enumerators work.

The code fragment below shows iterating through a collection using the foreach statement and then doing the same thing using an enumerator.  (dogs is of type List<Dog>).

            // Using foreach
            foreach (Dog d in dogs)

            // Using enumerator directly
            List<Dog>.Enumerator dogEnum = dogs.GetEnumerator();
            while (dogEnum.MoveNext())
                Dog d = (Dog)dogEnum.Current;

The enumerator is an object of type List<T>.Enumerator.  We call a method on the List<T> object to get an instance of its enumerator and then navigate through the list using the MoveNext method.  The Current property returns the object that the enumerator is currently pointing to.