Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerator.MoveNext() implementation?

I am kind of new to c# i know a method defined in a interface has to be implemented

but in the below code i have not implemented MoveNext() method

static void Main()
{
    List<int> list = new List<int>();
    list.Add(1);
    list.Add(5);
    list.Add(9);

    List<int>.Enumerator e = list.GetEnumerator();
    Write(e);
}

static void Write(IEnumerator<int> e)
{
    while (e.MoveNext())
    {
        int value = e.Current;
        Console.WriteLine(value);
    }
}

I checked in metadata too, & it does not provide any implementation.

so why is the compiler not throwing any error? where is the implementation of MoveNext() method & how does it move to next value?

Is the code for MoveNext() method auto generated by compiler? please help

like image 271
Arun Avatar asked Apr 15 '15 15:04

Arun


1 Answers

The reason is, you did not implement IEnumerator<int>, you used List<int> which has implemented it and provided implementation for MoveNext.

Here is the actual implementation and the code is:

public bool MoveNext() {

    List<T> localList = list;

    if (version == localList._version && ((uint)index < (uint)localList._size)) 
    {                                                     
        current = localList._items[index];                    
        index++;
        return true;
    }
    return MoveNextRare();
}
like image 70
Habib Avatar answered Oct 04 '22 09:10

Habib