#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)
                Console.WriteLine(d.Name);

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

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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #556 – Using an Enumerator Explicitly

  1. This explanation is very helpful. I’ve only ever seen enumeration explained with a foreach statement, so it’s nice to see what makes the magic work. 🙂

  2. Steven says:

    Sean – Great stuff. Thanks for sharing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: