How to use IEnumerable/IEnumerator

Posted by in C# category on for Intermediate level | Points: 250 | Views : 16488 red flag
Rating: 4.5 out of 5  
 4 vote(s)

This article describes use of IEnumerable interface for Collection types.


IEnumerable is an interface, implemented by System.Collecetion type in .Net that provides iterator pattern. The definition according to MSDN is:

“Exposes the enumerator, which supports simple iteration over non-generic collection.”

It’s something that you can loop over. That might be a List or Array or anything else that supports foreach loop.

IEnumerator allows you to iterate over List or array, and processes each element one by one


Explore usage of IEnumerable and IEnumerator for user defined class.


Let’s first show how both IEnumerable and IEnumerator works: Let’s define List of string and iterate each element using iterator pattern

// This is a collection that eventually we will use an Enumertor to loop through
// rather than a typical index number if we used a for loop.
List<string> Oceans = new List<string>();


Now, we already knows how to iterate each element using foreach loop 

// HERE is where the Enumerator is gotten from the List<string> object
foreach(string ocean in Oceans)
{     Console.WriteLine(ocean); }
// We can do same thing using IEnumerable/IEnumerator.

 IEnumerator enumerator = Oceans.GetEnumerator();
ocean = Convert.ToString(enumerator.Current);
So that's the first advantage there: if your methods accept an IEnumerable rather than an array or list they become more powerful because you can pass more different kinds of objects to them.

Second and most important advantage over List and Array is, unlike List and Array, iterator block hold a single item in memory, so if you are reading the result from large SQL query you can limit your memory use to single record. Moreover this evaluation is lazy. so if you're doing complicated work to evaluate the enumerable as your read from it, that work doesn't happen until it's asked for.

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Himanshu Manjarawala
Member Level: Bronze
Member Status: Member
Member Since: 7/30/2011 7:42:18 AM
Country: India
Himanshu Manjarawala Sr. Software Engineer@AutomationAnywhere
I am Himanshu Manjarawala, Graduate in Computer Science and MCA From Veer Narmad South Gujarat University, Surat Gujarat India. Currently working as Sr. Software Developer in Automation Anywhere.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)