Difference between IEnumerator and IEnumerable

By | December 12, 2017

IEnumerable
An enumerable class implements the IEnumerable interface. The IEnumerable interface has only one method GetEnumerator, which returns an IEnumerator interface.

public IEnumerator GetEnumerator();

Example:-

class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);

List<int>.Enumerator e = list.GetEnumerator();
Write(e);
}

static void Write(IEnumerator<int> e)
{
while (e.MoveNext())
{
int value = e.Current;
Console.WriteLine(value);
}
}
}

Output:-
1
2
3
4
5

IEnumerator
An Enumerator implements IEnumerator Interface. Enumerators only allow reading the data in the collection. Enumerators cannot be used to modify the underlying collection. It has two methods called MoveNext and Reset and a property called Current as below.

public object Current;

public void Reset();

public bool MoveNext();

Example:-

using System.Collections;
class MyColors : IEnumerable
{
 string[] Colors = { "Red", "Yellow", "Blue" };
 public IEnumerator GetEnumerator()
 {
 return new ColorEnumerator(Colors);//An instance of the enumerator class
 } 
}

The main difference between IEnumerable and IEnumerator is an IEnumerator retains its cursor’s current state.

Points to remember:-

  • Both are interface
  • IEnumerable code are clear and can be used in foreach loop
  • IEnumerator use While, MoveNext, current to get current record
  • IEnumerable doesn’t remember state
  • IEnumerator persists state means which row it is reading
  • IEnumerator cannot be used in foreach loop
  • IEnumerable defines one method GetEnumerator which returns an IEnumerator
  • IEnumerator allows readonly access to a collection

I hope you will enjoy the difference between IEnumerator and IEnumerable in C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

 

Like it? Share it