Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# Windows .NET
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...?!
Posted 22-Mar-13 0:06am
Velrats1.3K
Rate this: bad
good
Please Sign up or sign in to vote.

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

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.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 6,769
1 Sergey Alexandrovich Kryukov 6,338
2 DamithSL 5,408
3 Manas Bhardwaj 4,816
4 Maciej Los 4,195


Advertise | Privacy | Mobile
Web03 | 2.8.1411023.1 | Last Updated 22 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100