Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does foreach loop work in c# i-e MSIL? [duplicate]

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.

like image 811
Idrees Khan Avatar asked Mar 05 '26 14:03

Idrees Khan


1 Answers

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

like image 95
Romain Verdier Avatar answered Mar 07 '26 05:03

Romain Verdier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!