What does foreach use if a collection or list implements both IEnumerable<T> and IEnumerator<T>?
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) { }
IEnumerable<T> has a method GetEnumerator - this will be an IEnumerator<T>, which is what is used for iteration (using the MoveNext method).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With