The IEnumerator interface is used to set up a
collection for enumeration. To use for each, you cannot use the IEnumerator
interface. Therefore, the next step is to implement
another interface called IEnumerable. While the IEnumerator
interface is used to identify the class that holds each value that will be
visited, the IEnumerable interface is used to communicate with the
collection whose items will be enumerated. For this reason, when implementing
this interface, you should provide the means of accessing the external collection.
This can be done by passing a collection of the class that holds the values, to
a constructor of the IEnumerable implementer.

Getting the Enumerator

To implement the IEnumerable interface, start by
deriving a class from it. While the class implemented by the IEnumerator
interface represents an object, the class that implements the IEnumerable
interface is a collection. Here is an example:

The new class doesn't know what collection it
will be asked to enumerate. For this reason, in the new class, you should
declare a member variable of the class that holds the values that will be
enumerated. If the collection is array-based, you can create the member variable
as
follows:

Eventually, when instantiating the IEnumerable
implementer, you will need to pass it a collection of values. To make this
possible, you can create a method in the new class and pass that collection of
objects. Here is an example:

To support the use of the for each loop, the IEnumerable
interface is equipped with (only) a (one) method named GetEnumerator that you
must implement. The IEnumerable::GetEnumerator() method returns an IEnumerator
object:

When implementing this method, you can return an object of the class
that implements the IEnumerator interface, passing it the collection that was
declared in the IEnumerable implementer. This can be done as follows:

To enumerate the collection, declare a variable based on the
implementer of the IEnumerable and pass the collection to its
constructor.
Once this is done, you can then use the for each. Here is an example: