2

Possible Duplicate:
How do foreach loops work in C#?

Just like classic iterative statments like for, while or do-while, is foreach loop is a new loop statment in c#? or in other languages such as php

OR

behind the scenes it translate our code to for, while or do-while loop.

Community
  • 1
  • 1
Idrees Khan
  • 7,702
  • 18
  • 63
  • 111
  • What do you mean with "behind the scenes"? Are you talking about what MSIL looks like? – Candide Jul 03 '12 at 18:07
  • Yes, it get's translated, but not to a native loop. See [iterators](http://en.wikipedia.org/wiki/Iterator). And in fact, it uses some kind of duck typing -- it only requires the iterated object to have a method `GetEnumerator`. – phipsgabler Jul 03 '12 at 18:12
  • yes, i m talking about IL code – Idrees Khan Jul 03 '12 at 18:14

3 Answers3

8

The foreach construction is equivalent to:

IEnumerator enumerator = myCollection.GetEnumerator();
try
{
   while (enumerator.MoveNext())
   {
       object current = enumerator.Current;
       Console.WriteLine(current);
   }
}
finally
{
   IDisposable e = enumerator as IDisposable;
   if (e != null)
   {
       e.Dispose();
   }
}

Note that this version is the non generic one. The compiler can handle IEnumerator<T>.

Romain Verdier
  • 12,833
  • 7
  • 57
  • 77
4

Its not a new loop. Its been around since beginning.

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.

class ForEachTest
{
    static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };

        foreach (int i in fibarray)
            System.Console.WriteLine(i);
    }

}

Output

0
1
2
3
5
8
13

Unlike for loop which is used for index and accessing value like array[index], foreach works directly on value.

More here

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • It wasn't in the 1.x versions? Strange... – Austin Salonen Jul 03 '12 at 18:06
  • 3
    That's not correct. It's been there since the beginning. Here's a link to the 1.x version of the ECMA language specification http://www.ecma-international.org/publications/files/ECMA-ST-WITHDRAWN/ECMA-334,%202nd%20edition,%20December%202002.pdf – Brian Rasmussen Jul 03 '12 at 18:10
0

It is a while loop infact and it uses GetEnumerator() method of container, see http://msdn.microsoft.com/en-us/library/aa664754(v=vs.71).aspx for details.

For arrays it is optimized to use indexer.

Alexey F
  • 1,763
  • 14
  • 19