Click here to Skip to main content
14,876,344 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I'm a newbie programmer

I just wanted to know the difference between Foreach loop and enumerator.

My confusion lies in here.

Both the codes give same output but why enumerator is preferred over foreach loop in some programs...?!

foreach is just a shortcut, that simplifies performing the collection enumeration. From[^], 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.
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.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900