Loading ...

Implementation of C# foreach loop | CodeAsp.Net

Implementation of C# foreach loop

0 (0votes)

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:

int[] array = { 5, 10, 15, 20, 25 };
foreach (int number in array)
    Response.Write(number + ",");

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”

int[] array = { 5, 10, 15, 20, 25 };
System.Collections.IEnumerator enumerator = array.GetEnumerator();
while (enumerator.MoveNext())
    Response.Write(enumerator.Current + ",");

As you can see, an IEnumerator is used.

The implementation is completely equal when we have generic collection, for example List<T>.


List<int> list = new List<int>();
System.Collections.IEnumerator enumerator = list.GetEnumerator();            
while (enumerator.MoveNext())
    Response.Write(enumerator.Current + ",");

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,

Comments (no comments yet)

  • :*
  • :*
  • :

Top Posts