Distinction between iterator and enumerator

An interview question for a .NET 3.5 job is "What is the difference between an iterator and an enumerator"?

This is a core distinction to make, what with LINQ, etc.

Anyway, what is the difference? I can't seem to find a solid definition on the net. Make no mistake, I can find the meaning of the two terms but I get slightly different answers. What would be the best answer for an interview?

IMO an iterator "iterates" over a collection, and an enumerator provides the functionality to iterate, but this has to be called.

Also, using the yield keyword is said to save state. What exactly is this state? Is there an example of this benefit occurring?


Iterating means repeating some steps, while enumerating means going through all values in a collection of values. So enumerating usually requires some form of iteration.

In that way, enumerating is a special case of iterating where the step is getting a value from a collection.

Note the "usually" – enumerating may also be performed recursively, but recursion and iteration are so closely related that I would not care about this small difference.

You may also enumerate values you do not explicitly store in a collection. For example, you can enumerate the natural number, primes, or whatever but you would calculate these values during the enumeration and not retrieve them from a physical collection. You understand this case as enumerating a virtual collection with its values defined by some logic.


I assume Reed Copsey got the point. In C# there are two major ways to enumerate something.

  1. Implement Enumerable and a class implementing IEnumerator
  2. Implement an iterator with the yield statement

The first way is harder to implement and uses objects for enumerating. The second way is easier to implement and uses continuations.


In C# 2+, iterators are a way for the compiler to automatically generate the IEnumerable and/or IEnumerable<T> interfaces for you.

Without iterators, you would need to create a class implementing IEnumerator, including Current, MoveNext, and Reset. This requires a fair amount of work. Normally, you would create a private class that implemtented IEnumerator<T> for your type, then yourClass.GetEnumerator() would construct that private class, and return it.

Iterators are a way for the compiler to automatically generate this for you, using a simple syntax (yield). This lets you implement GetEnumerator() directly in your class, without a second class (The IEnumerator) being specified by you. The construction of that class, with all of its members, is done for you.

Iterators are very developer friendly - things are done in a very efficient way, with much less effort.

When you use foreach, the two will behave identically (provided you write your custom IEnumerator correctly). Iterators just make life much simpler.