

But IEnumerator is a read-only, forward-only cursor over a collection of values and can retain the current cursor state.

IEnumerable can only return IEnumerator, IEnumerable cannot retain the cursor's current state. IEnumerable has only one method ( GetEnumerator), whereas IEnumerator has two methods ( MoveNext and Reset). Iterating over a collection is made simple in c# with the use of foreach keyword which enumerates a collection, executing the embedded statement once for each element in the collection:īasic Differences Between IEnumerable and IEnumerator IEnumerator provides the ability to iterate through the collection by exposing. IEnumerable contains only one method, GetEnumerator, which returns an IEnumerator or IEnumerator which supports a simple iteration over a non-generic and generic collection respectively. To use generic version of IEnumerable we can use IEnumerable. In C# IEnumerable is the base interface for all collections that can be iterated on. Iterator Design Pattern is used in every modern programming language to step through data structures or collections to provide some kind of iterator for example in C# foreach() that allows programmers or developers to iterate through its objects, without knowing underlying implementation.
#ICOLLECTIONS HOW TO#
Now what is an iterator? Simply put it is an object which defines how to iterate over a collection and what is the next element we can iterate to (Move Next). At any time we use a loop to go through a collection of rows it is called an iteration.Įnter fullscreen mode Exit fullscreen mode

In its most basic form, iteration means taking each element at a time in a collection of elements and going through them one after another. To understand iterators we need to understand what iteration means. They all implement Iterator Pattern to iterate on a set of rows or collection of rows, so what is iteration and iterator. In C# we got different interfaces to handle collections for example IList, ICollection, IDictionary, IEnumerable etc.
