Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When IEnumerator.Reset() method is called?

Tags:

c#

interface

let's have this code :

class MyList : IEnumerable, IEnumerator
{
    int[] A = { 1, 2, 3, 4, 5 };
    int i = -1;

    #region IEnumerator Members

    public object Current
    {
        get { return A[i]; }
    }

    public bool MoveNext()
    {
        i++;
        return i < 5;
    }

    public void Reset()
    {
        i = -1;
    }

    #endregion

    #region IEnumerable Members

    public IEnumerator GetEnumerator()
    {
        return (IEnumerator)this;
    }

    #endregion
}

And In Main Method :

MyList list = new MyList();
foreach (int i in list)
{
    Console.WriteLine(i);
}

foreach (int i in list)
{
    Console.WriteLine(i);
}

Why the second foerach doesn't work ?? and the "i" doesn't initialize again ??

Is that true : Reset method should be called automatically before foreach is executed ??

why it doesn't call here ??

like image 694
Farah_online Avatar asked Oct 16 '10 05:10

Farah_online


People also ask

Is IEnumerator a method?

If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic). IEnumerable has just one method whereas IEnumerator has two methods (MoveNext and Reset) and a property Current.

What is an IEnumerator?

IEnumerator is an interface, which when implemented allows you to iterate through the list of controls. To implement it requires that you provide two methods - Reset to go back to the beginning of the list, and MoveNext to move forward, and Current to get the current item.

What is difference between IEnumerable and IEnumerator in C#?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. This works for readonly access to a collection that implements that IEnumerable can be used with a foreach statement. IEnumerator has two methods MoveNext and Reset. It also has a property called Current.


1 Answers

Reset is redundant; so much so that it is a requirement in the language spec for iterator blocks to throw an exception on Reset. The correct thing to do is simply dispose and release the old iterator, and call GetEnumerator again. Or better: avoid having to read it twice, since not all data is repeatable.

like image 145
Marc Gravell Avatar answered Oct 11 '22 02:10

Marc Gravell