top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between IEnumerator and IEnumerable?

+3 votes
423 views
What is the difference between IEnumerator and IEnumerable?
posted Jun 26, 2015 by Manikandan J

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes

IEnumerable

public IEnumerator GetEnumerator();

IEnumerator

public object Current;
public void Reset();
public bool MoveNext();

IEnumerable and IEnumerator are both interfaces. IEnumerable has just one method called GetEnumerator. This method retuns (as all methods return something including void) another type which is an interface and that interface is IEnumerator. When you implement enumerator logic in any of your collection class, you implement IEnumerable (either generic or non generic). IEnumerable has just one method whereas IEnumerator has 2 methods (MoveNext and Reset) and a property Current. For easy understanding consider IEnumebale a box that contains IEnumerator inside it (though not through inheritance or containment). See the code for better understanding:

class Test : IEnumerable, IEnumerator
{
     IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
    public object Current
    {
        get { throw new NotImplementedException(); }
    }

    public bool MoveNext()
    {
        throw new NotImplementedException();
    }
    public void Reset()
    {
        throw new NotImplementedException();
    }
}
answer Jun 29, 2015 by Shivaranjini
...