C# foreach loop

C# has a new iteration syntax called foreach, which I believe has been inherited from Visual Basic ( correct me if I am wrong).

The foreach syntax is not found in Java. However, this is not a big leap ahead for C#. I say so, because foreach is nothing but a hardwired while statement block!

Consider the following code snippet:

foreach(int i in a)
{
Console.WriteLine(i);
}

This is equal to the while loop, given below :

a = x.GetEnumerator();
while(a.MoveNext())
{
Console.WriteLine(a.Current);
}

The actual test code can be found in TestForeach.cs, attached with this article.

The C# compiler implements the foreach syntax, just as it would compile the while loop above!

This is what happens in the background. Before entering the statement block, the compiler generates the code to call the virtual method GetEnumerator of the object passed as the second parameter in the foreach statement.The GetEnumerator method must return an object, having a property named Current, of type similar to the first argument of the foreach. Also this object must have a MoveNext method of return type bool. This method informs the runtime when to terminate the loop.

How do I know? You do not have to take my word for it.

To verify just compile the file:

csc TestForeach.cs

The above command will produce TestForeach.exe.
Then use the ildasm command:

ildasm TestForeach.exe

Then in the GUI tree view, click on the Main code segment to view the similarity of the generated code.

However, if you wish to interop with other Dot Net languages, say with VB.NET, the collection class must implement the interface,  System.Collections.IEnumerable and the enumerator should implement the interface System.Collections.IEnumerator.


Further Readings on Loops and Control Statements in C#