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)