The
foreach
statement repeats a group of embedded statements for each element in an array or an object collection that implements theSystem.Collections.IEnumerable
orSystem.Collections.Generic.IEnumerable<T>
interface.
I understand that if we want to use foreach on an object collection, we need to implement IEnumerable on it.
I want to understand how does implementin IEnumerable enable the usage of 'foreach'?
The source code of IEnumerable seems to have only one function 'GetEnumerator', and obviously there is no implementation because IEnumerable is an interface - So how does the foreach keyword actually use IEnumerable interface for enumeration?
Edit: Also trying to understand it in this context:
IEnumerable<Int> myNumbers = new IEnumerable<Int>();
Which GetEnumerator() is called/used here?
Edit 2:
So the answer seems to be:
1: DuckTyping -- (thanks @Alexei Levenkov. I accepted @horrorcat as an answer because I can accept only one :) )
2. I made an obvious mistake in trying to create a concrete instance of an interface (in the second part of my question) -- (thanks @Gary Vass)