I am trying to understand the IEnumerable
interface in C#. As it is stated in MSDN
IEnumerable
exposes an enumerator, which supports a simple iteration over a non-generic collection. This is quite simple. When we have a collection that implements this interface then, we get an enumerator, which implements the IEnumerator
interface, (http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator(v=vs.110).aspx), and the using this enumerator we can iterate through all the elements of the collection in a way like the below:
foreach(var item in items)
{
// code goes here
}
In the above snippet of code, items
is a collection that implements the IEnumerable
interface. This is possible because the enumerator has a property called Current
, which has the current element of the collection and a method MoveNext
, which is used by the enumerator, to move to the next element. Last but not least, it has a method called Reset
, which sets the enumerator to its initial position, which is before the first element in the collection, as it is stated in MSDN.
Let we have the following snippet of code:
int[] array = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
IEnumerable<int> numbers = array;
foreach (var number in numbers)
{
Console.WriteLine(number);
}
In the above snippet of code we initialize an array of integers and then we define a type of IEnumerable
that points to the array. Since numbers
implements the IEnumerable
, we can iterate through it's elements using the above foreach
.
I think that the compiler behind the scenes emits some code, when we define the numbers
and then try to iterate through it's elements. Actually I found that Array
implements IEnumerable<T>
.
My question is every time we define an array, since an array is an object that implements IEnumerable
and IEnumerator
, the corresponding methods are implemented by the compiler?
Thanks in advance for any help !