Pregunta

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 ?

¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top