Difference Between IEnumerator And IEnumerable

Here we are going to find  out about the difference between IEnumerator and IEnumerable in C#.

Firstly, create a new project whose name is IenumerbleVsIenmerator, I created a list of string and some string values like this:


After that I read values from namelist using IEnumerator.

Convert list into IEnumerator and print it,



Output 


After that you can see the name list using IEnumerable. Firstly, convert name list into IEnumberable list like this.


Here's the output:


Now we can see that same name list print using IEnumerator and IEnumerable, both output are same here but code is different. Here we can see the code difference.


Clearly we can find out the difference between codes,

In IEnumerator list uses while loop but IEnumerable list uses foreach loop; the second thing is that in while loop IEnumeratornamelist contains .Current method but IEnumerablenamelist does not contain it.

And we can see more differences.

IEnumeratornamelist contains some methods shown below.


But IEnumerablenamelist list does not contains movenext (),


Without using any method it prints name list code like this.


If we want to print those names which start from A and B first after that C and D using IEnumerator and IEnumerable different methods like here.

Using IEnumerator:

First method nameFirstA2B prints name which starts from and A and B. But nameFirstC2D prints name which starts from C and D. When it checks condition if nameall equal Bheem then call nameFirstC2D it means IEnumerator contains his position that which position condition is true then it goes to nameFirstC2D with his position and works on behalf of position.


 

Using IEnumerable methods : here condition is checked that name ==”Bheem” then go to nameFirstC2D method and it should contain Chandani because it comes after Bheem but if it contains Amit it means it again initialized from the beginning of nameall (0 index).



Here the first main difference is that IEnumerator contains his position but IEnumerable does not.

Second difference


Go to IEnumerable definition IEnumerable internally call IEnumerator


Conclusion:

1. IEnumerator always contains his position (state) which index is stay but IEnumerable does not.

2. IEnumerable internally call IEnumerator.

3. IEnumerable is easier for developes to use and write less code.

Read more articles on C#:


Similar Articles