Question

I read about IEnumerable:

IEnumerable or IEnumerable<T> : by implementing this an object states that it can give you an iterator that you can use to traverse over the sequence/collection/set

So, the foreach statement uses only the IEnumerable interface to iterate over a collection ?

Or does it use IEnumerator too ?

Was it helpful?

Solution

IEnumerable exposes a single method, which returns an IEnumerator. So, the answer is: it uses both.

OTHER TIPS

IEnumerator does not expose GetEnumerator so a foreach will throw an error.

IEnumerable numbers = new[]{1,2,3,4,5};
foreach(var number in numbers) //finds GetEnumerator()
{
    Console.WriteLine(number);
}

IEnumerator numbers2 = new[]{1,2,3,4,5}.GetEnumerator();
foreach(var number in numbers2) //cannot find GetEnumerator, throws
{
    Console.WriteLine(number);
}

The second foreach will throw an error because foreach is specifically looking for the GetEnumerator method which is not exposed on IEnumerator its self.

If you look at the IEnumerable interface, you will find out that its only method is to get IEnumerator to iterate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top