IEnumerable VS IEnumerator in C#

Introduction

First let's see a small demonstration of both of these interfaces and then we will talk about the differences.

DEMO

Create a new console application and in the main method add the following.

static void Main(string[] args)
{  
   List<string> Month = new List<string>();  
   Month.Add("January");  
   Month.Add("February");  
   Month.Add("March");  
   Month.Add("April");  
   Month.Add("May");  
   Month.Add("June");  
   Month.Add("July");  
   Month.Add("August");  
   Month.Add("September");  
   Month.Add("October");  
   Month.Add("November");  
   Month.Add("December");  
} 

In our main method, we created a new list collection “Month” of type string. In this collection we added all the 12 months as items in this list.

Note: The List class is present in the System.Collections.Generic namespace.

Now let's create a very simple IEnumerable on this list.

//create IEnumerable of string 
IEnumerable<string> iEnumerableOfString = (IEnumerable<string>)Month;  
  
//If we want to retrieve all the items from this IEnumerable object, we can use a foreach loop. 
foreach(string AllMonths in iEnumerableOfString)
{  
   Console.WriteLine(AllMonths);  
}

Run the application.

IEnumerable VS IEnumerator in C#

We got the list of months.

Now let's see how to do the same, using an IEnumerator and then we will see the differences.

//Create IEnumerator of string.
 
IEnumerator<string> iEnumeratorOfString = Month.GetEnumerator();//to convert list into IEnumerator we can invoke the GetEnumerator method  
  
//To retrieve all the items from the above IEnumerator object, we cannot use foreach loop instead of that we need to invoke MoveNext() Boolean method.  
while(iEnumeratorOfString.MoveNext())
{  
  
}

To display the items on the console window we need to invoke the Current property as in the following:

while(iEnumeratorOfString.MoveNext())  
{  
   Console.WriteLine(iEnumeratorOfString.Current);  
}

Run the application.

IEnumerable VS IEnumerator in C#

Similarities

Both of these interfaces help to loop through the collection.

So, now the next question is, what should I use?

As we know, both of these interfaces give the same result. But if you watch the syntax for IEnumerable, it is very simple.

foreach(string AllMonths in iEnumerableOfString)  
{  
   Console.WriteLine(AllMonths);  
}

But in the case of IEnumerator, we need to invoke the MoveNext method and to retrieve the current item, we need to invoke the current property.

Relation

The IEnumerable interface actually uses IEnumerator. The main reason to create an IEnumerable is to make the syntax shorter and simpler.

If you go to the definition of the IEnumerable<T> interface, you will see this interface has a method GetEnumerator() that returns an IEnumerator object back.

IEnumerable VS IEnumerator in C#

In short, this IEnumerable uses IEnumerator internally.

Differences

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

Let's understand this practically.

Create two static methods in the main program.

static void iEnumeratorMethodOne(IEnumerator<string> i)  
{  
   while(i.MoveNext())  
   {  
      Console.WriteLine(i.Current);  
  
       if(i.Current == "June")  
       {  
          iEnumeratorMethodTwo(i);  
       }  
    }  
}  
  
static void iEnumeratorMethodTwo(IEnumerator<string> i)  
{  
    while(i.MoveNext())  
    {  
       Console.WriteLine(i.Current);  
     }  
}

Explanation

  1. In the iEnumeratorMethodOne method, we added a parameter “i” of type IEnumerator of string.
  2. Inside the method block, we used a while loop to move to the next item using the MoveNext method and if the item is found then we invoked the Current property that will provide us the current item and we are displaying that item on the console window.
  3. In the if block we are checking the current item state, if the item is “June” then we invoke the second iEnumerator method and in that method we passed the IEnumerable of string object. In other words, i.
    Then invoke this method in the main method and pass an iEnumeratorOfString as a parameter argument.
IEnumerator<string> iEnumeratorOfString = Month.GetEnumerator();  
iEnumerableMethodOne(iEnumeratorOfString); 

Put a breakpoint on both the iEnumeratorMethods and press F10.

Look at the current item; it is January.
IEnumerable VS IEnumerator in C#

In the if block, the current item is being compared with the item “June”. Once the current item is June then it will invoke the second method.

Press F10 until the current item reaches June.

IEnumerable VS IEnumerator in C#

So, now the current item is June which means the if block will be executed and this block will invoke iEnumeratorMethoTwo.

IEnumerable VS IEnumerator in C#

Look at the current item present in the i object, “June”.

Once this iEnumeratorMethoTwo executes, look at the current item.

IEnumerable VS IEnumerator in C#

It's July.

IEnumerable VS IEnumerator in C#

Then August and so on.

So, IEnumerator retains its cursor state.

In the end we will get the following result.

IEnumerable VS IEnumerator in C#

So, if you want to loop sequentially through the collection, use an IEnumerable interface else if you want to retain the cursor position and want to pass it from one function to another function then use an IEnumerator interface.

Summary

In this article, we learned about the IEnumerable and IEnumerator interfaces.

I hope you like it. Thank you.

Read more on IEnumerable in C#


Similar Articles