IEnumerable and IEnumerator in C# with example

We will discuss here what is IEnumerable, IEnumerator, what are differences between them, where should we use IEnumerable and where to IEnumerator, once we will finish our discussion it will be clear, which one would be best for which situation and why, so let’s see it with example
To better understand we will create a list of age
List<int> ages = new List<int>();
ages.Add(10);
ages.Add(20);
ages.Add(30);
ages.Add(40);
ages.Add(50);
Now convert this list to IEnumerable
IEnumerable<int> age_IEnumerable = (IEnumerable<int>)ages;
foreach (int age in age_IEnumerable)
    Console.WriteLine(age);
There is nothing new, we used foreach here very straight forward, now let’s convert the ages into IEnumerator, there is a method GetEnumerator to convert a list into IEnumerator
IEnumerator<int> age_IEnumerator = ages.GetEnumerator();
while (age_IEnumerator.MoveNext())
    Console.WriteLine(age_IEnumerator.Current);
As you can see here we used while rather than foreach because foreach cannot be used with IEnumerator, but still there is nothing which can suggest us when should we use IEnumerable and where to IEnumerator.
Before we go further, we should know, IEnumerable uses IEnumerator internally also have a function GetEnumeratorto convert into IEnumerator, we should use IEnumerable because it make coding easier and clearer as we can see in above example.
Now let’s discuss the main difference, IEnumerable doesn’t remember the state, which row or record it is iterating while IEnumerator remember it and we are going to see this with example by creating method PrintUpto30 and PrintGreaterThan30
Let’s first check with IEnumerator

As we know IEnumerator persists state so once we will call PrintGreaterThan30 by passing
age_IEnumerator it will print the remaining list, here is the output:

Now let’s check same code with IEnumerable

Now check the output you will see “PrintGreaterThan30 is called” many times something like this


Conclusion:
  1. Both are interface
  2. IEnumerable code are clear and can be used in foreach loop
  3. IEnumerator use While, MoveNext, current to get current record
  4. IEnumerable doesn’t remember state
  5. IEnumerator persists state means which row it is reading
  6. IEnumerator cannot be used in foreach loop
  7. IEnumerable defines one method GetEnumerator which returns an IEnumerator
  8. IEnumerator allows readonly access to a collection

No comments:

Post a Comment