Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does foreach prefer IEnumerable<T> or IEnumerator<T>

What does foreach use if a collection or list implements both IEnumerable<T> and IEnumerator<T>?

like image 826
Beachwalker Avatar asked Dec 07 '25 04:12

Beachwalker


2 Answers

You can't use a foreach on an IEnumerator<T> at all.

You can only foreach over an object that has a GetEnumerator method (whether or not it implements IEnumerable.

So to answer your question, it uses the GetEnumerator method from IEnumerable<T>.

It's simple to prove. Just try to compile this:

IEnumerator<char> str = "asdf".GetEnumerator();
foreach (char c in str) { }
like image 91
Servy Avatar answered Dec 08 '25 17:12

Servy


IEnumerable<T> has a method GetEnumerator - this will be an IEnumerator<T>, which is what is used for iteration (using the MoveNext method).

like image 33
Oded Avatar answered Dec 08 '25 17:12

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!