Hi Friends,

Today in this section, we’ll see IEnumerable in action and will see that how it actually works and holds true for all collection. As i already said in one of my posts that collection don’t iterate itself, they need enumerators to loop through and its IEnumerable‘s job to provide the enumerators. so, whenever we loop any collection under foreach(), we are actually invoking IEnumarable to get the enumerator. So, IEnumerable exposes only one method and that is GetEnumerators().

Here, enumerator uses three basic properties to iterate in the list and that is MoveNext(),reset and Current. MoveNext() will iterate till the collection ends and Current will set the subsequent item to current. Now, let’s see the same in action.


Now, consider the scenario of foreach(). As shown below in the example foreach() is pretty straight forward, i could have used the same in main method directly as i was using in the previous examples. However, i just wanted to emphasize on one point that foreach() internally replaces the code with with the previous example of IEnumerator.

and offcourse result will be the same only.


Now, there is one exception to this, if the compiler notices that collection which we are iterating through is Array, then it will simply convert the foreach() method to to for loop than IEnumeartor implementation, as this is the most efficient way of iterating through. But, this only holds for arrays.

One more point is, enumeration is read only operation, so if you tries to modify the collection on the fly and iterate through, this won’t allow.


However, the above restriction is not applicable for all the collections. For example, if i change the same to Array and run the again, then compiler won’t complain. However, one point to note that its not a good practice to modify the element while iterating and the reason for this is foreach() for arrays gets converted into for loop, hence modification allowed in that.

Thanks for joining me.

Rahul sahay,
Happy Coding

This entry was posted in C# and tagged . Bookmark the permalink.

One thought on “IEnumerable

Comments are closed.