Introduction
IEnumerable
is an interface implemented by the System.Collecetion
type in .NET that provides
the Iterator pattern. The definition according to MSDN is:
“Exposes the enumerator, which supports simple iteration over non-generic collections.”
It’s something that you can loop over. That might be a List
or Array
or anything else that supports a foreach
loop.
IEnumerator
allows you to iterate over List
or Array
and process each element one by one.
Objective
Explore the usage of IEnumerable
and IEnumerator
for a user defined class.
Using the code
Let’s first show how both IEnumerable
and IEnumerator
work: Let’s define a List
of string
s and iterate
each element using the iterator pattern.
string[] Continents = new string[] { "Asia", "Europe", "Africa", "North America", "South America", "Australia", "Antartica" };
Now we already knows how to iterate each element using a foreach
loop:
foreach(string continent in Continents)
{
Console.WriteLine(continent);
}
The same can be done with the IEnumerator
object.
IEnumerator enumerator = Continents.GetEnumerator()
while(enumerator.MoveNext())
{
string continent = Convert.ToString(enumerator.Current);
Console.WriteLine(continent);
}</string>
Points of Interest
That's the first advantage: if your methods accept an IEnumerable
rather than an Array
or List
, they become more powerful
because you can pass different kinds of objects to them.
The second and most important advantage over List
and Array
is, unlike List
and Array
, an iterator block holds
a single item in memory, so if you are reading the result from a large SQL query, you can limit your memory use to a single record. Moreover this evaluation is lazy.
So if you're doing a complicated work to evaluate the enumerable as you read from it, the work doesn't happen until it's asked for.
I am Himanshu Manjarawala, Garduate in Computer Science and MCA From Veer Narmad South Gujarat University, Surat Gijarat India. Currently working as Sr. Software Developer in Automation Anywhere Softwares Pvt. Ltd. Vadodara, Gujarat