0

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 ?

3 Answers3

3

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

jmoreno
  • 12,752
  • 4
  • 60
  • 91
  • 1
    +1. To be precise - it uses both if it gets object that implements `IEnumerable` - otherwise tries [duck typing](http://stackoverflow.com/questions/6368967/duck-typing-in-the-c-sharp-compiler) for matching methods. – Alexei Levenkov Oct 23 '13 at 05:51
  • @AlexeiLevenkov: great link. So, it makes clear that the `foreach` will even work if a class does not implement `IEnumerable` and `IEnumerator` but has the required `GetEnumerator()`, `MoveNext()`, `Current` and `Reset` methods. – now he who must not be named. Oct 23 '13 at 05:58
0

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.

Cubicle.Jockey
  • 3,288
  • 1
  • 19
  • 31
0

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

Junfeng Dai
  • 116
  • 2