2 solutions

Solution 2

foreach is just a shortcut, that simplifies performing the collection enumeration. From http://support.microsoft.com/kb/307484[^], which describes how to create a custom collection (implementing IEnumerable):

How does this work? For Each calls the GetEnumerator method to create the Enumerator object and calls the MoveNext method to set the cursor to the first item. Then the Current property is accessed to get the item in MyObj. This is repeated until MoveNext returns False.

In other words, your collection implements the IEnumerable interface, which requires a GetEnumerator method. This GetEnumerator method returns an IEnumerator that knows how to do the actual enumeration, traversing your collection.

Solution 1

No. These things are complementary. Enumerators (and enumerables) can be used to get elements one by one from a non-indexable, or not pre-filled set. The foreach is the kind of loop you can use to traverse these sets. You can not use for loops since you can not rely on indexes. You could however user the methods exposed by the implemented interfaces an some while loop - but foreach is much more simpler.