What is the difference between IEnumerator and IEnumerable?

IEnumerator makes looping over a collection possible. IEnumerable provides GetEnumerator() method that returns an instance of IEnumerator

IEnumerator is an interface from the Systems.Collection namespace which provides the infrastructure to allow the caller to iterate over the internals of the implementing type. It supports a simple iteration over a non-generic collection.

IEnumerator interface has methods to implement –

  • MoveNext() and
  • Reset()

and also a property Current which all help in iterating through the non-generic collection that implements Enumerator.

an instance of type IEnumerator is provided by the GetEnumerator() method which is present in the IEnumerable interface.

For example, if you have a variable of type IEnumerable<Book> and you iterate over this collection variable as below –

IEnumerable<Book> items = new List<Book>();
foreach (var item in items)
{
    // some code to access item of type Book
}

The above code snippet is equivalent to the below –

IEnumerable<Book> items = new List<Book>();

var itemsEnumerator = items.GetEnumerator();
Book item;

while (itemsEnumerator.MoveNext())
{
   item = (Book)itemsEnumerator.Current;
   // some code to access item of type Book
}

The IEnumerable interface enables the implementing type to be iterated by providing an appropriate Enumerator instance of it.

A type can be used over a foreach loop only if it implements an IEnumerable (which supplies the required IEnumerator instance)

Sriram Mannava
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply

Your email address will not be published. Required fields are marked *