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 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1. To be precise - it uses both if it gets object that implements IEnumerable - otherwise tries duck typing for matching methods.
@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.
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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.