Click here to Skip to main content
11,641,971 members (58,200 online)
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 21-Mar-13 23:06pm
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 DamithSL 245
1 Afzaal Ahmad Zeeshan 170
2 Sergey Alexandrovich Kryukov 159
3 OriginalGriff 110
4 Mika Wendelius 90
0 Mika Wendelius 460
1 DamithSL 353
2 OriginalGriff 315
3 Sergey Alexandrovich Kryukov 179
4 Afzaal Ahmad Zeeshan 169


Advertise | Privacy | Mobile
Web01 | 2.8.150731.1 | Last Updated 22 Mar 2013
Copyright © CodeProject, 1999-2015
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