Question

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface.

I understand that if we want to use foreach on an object collection, we need to implement IEnumerable on it.

I want to understand how does implementin IEnumerable enable the usage of 'foreach'?

The source code of IEnumerable seems to have only one function 'GetEnumerator', and obviously there is no implementation because IEnumerable is an interface - So how does the foreach keyword actually use IEnumerable interface for enumeration?

Edit: Also trying to understand it in this context:

IEnumerable<Int> myNumbers = new IEnumerable<Int>();

Which GetEnumerator() is called/used here?

Edit 2:

So the answer seems to be:
1: DuckTyping -- (thanks @Alexei Levenkov. I accepted @horrorcat as an answer because I can accept only one :) )
2. I made an obvious mistake in trying to create a concrete instance of an interface (in the second part of my question) -- (thanks @Gary Vass)

Was it helpful?

Solution

IEnumerable.GetEnumerator() returns an enumerator object (which implements IEnumerator). This has a property "Current" which returns the current item, and a method "MoveNext()" which advances the enumerator on to the next item.

This is all the foreach loop needs to perform the foreach. It simply assigns the "Current" property to a variable then executes .MoveNext() each time.

Usually, when you implement IEnumerable on a class, you know where the source is coming from. So if you had a class such as this

public class MyEnumerable
{
    private List<string> items;
}

The implementation of IEnumerable would look like this

public class MyEnumerable : IEnumerable<string>
{
    private List<string> items;

    public IEnumerator<string> GetEnumerator()
    {
        return items.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return items.GetEnumerator();
    }
}

Notice that the enumerator is coming from the list object so you don't have to worry about creating an enumerator (though you can if you need to by implementing IEnumerator)

OTHER TIPS

foreach calls IEnumerable.GetEnumerator() (if collection implements one) or looks for GetEnumerator() method that returns duck-typed matching iterator class.

Than iterates over elements using the result of GetEnumerator() call, casting each element to type specified in first parameter of foreach.

as Lukazoid said "The implementer of IEnumerable implements the method GetEnumerator(), the foreach calls this method and then uses the resulting IEnumerator to iterate over the elements."

foreach only uses the Interface IEnumerable/IEnumerable<>, I think of this as a C# short cut for writing a 'readonly' for loop which you can use the data but not edit it.

also I found this, here on stackoverflow //which may make this question a dup

What's going on behind the scene of the 'foreach' loop?

Foreach is just sytactic sugar to enable using IEnumerable types. Code like:

foreach (var item in collection)
{
    ...
}

Is translated by the compiler to something like:

using (var enumerator = collection.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var item = enumerator.Current;
        // loop contents here
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top