Previously in the forums here, a member asked about the internal structure of
the FOREACH cycle, and how it is implemented.
Quite interesting questions especially for all C# / ASP.NET developers who
use this method a lot but haven’t thought of its implementation.
We already know that the FOREACH loop in C# help us to
iterate through elements on a given collection on the simplest possible way so
that we can easily access the elements of the collection and do some operations
inside the loop.
Actually, in some more complicated scenarios,the foreach cycle is an
incredible replacement of the standard FOR cycle.
The simplest implementation of FOREACH would be:
It’s an array with five elements. Using foreach cycle we are looping through
each element of the array and write them on the page.
Here is how the code is implemented “behind the scene”
As you can see, an IEnumerator is used.
The implementation is completely equal when we have generic collection, for
With using the MoveNext() method we are traveling through each element of the
collection, and with Current property we take the value of the current element.
So, that’s it.I hope this was an useful blog for you.
Kind Regards, Hajan