Internals of Foreach Loop in C#

For-Each Loop

To understand the working behind foreach loop, you first need to understand the basics of IEnumerable.

If any collection used foreach loop to iterates their elements, must implements IEnumerable interface.

In .NET, a collection implementing IEnumerable must implement a method called GetEnumerator which returns an IEnumerator.

For example: In the Generic List this will implement like this.

Returns an enumerator that iterates through the System.Collections.

public List<T>.Enumerator GetEnumerator();

Then, IEnumerator interface consists the following properties and methods.

public interface IEnumerator<out T>
{
    Current { get; }
    bool MoveNext();
    void Reset();
}

MoveNext :You to use the method to point to the next location.
Current: holds the current value of the collection.
Reset: allows you to re-initialize the cursor.

For Example:

var enumerable = Enumerable.Range(1, 100);
IEnumerator<int> enumerator = enumerable.GetEnumerator();
try
{
    while (enumerator.MoveNext())
    {
        int element = enumerator.Current;
    }
}
catch()
{
}

Ebook Download
View all
Learn
View all