Thursday, March 29, 2012

How to use the IEnumerable/IEnumerator interfaces

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 strings and iterate each element using the 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> Continents = new List<string>();

Continents.Add("Asia");
Continents.Add("Europe");
Continents.Add("Africa");
Continents.Add("North America");
Continents.Add("South America");
Continents.Add("Australia");
Continents.Add("Antartica");
Now we already knows how to iterate each element using a foreach loop:

// Here is where loop iterate over each item of collection
foreach(string continent in Continents)
{
    Console.WriteLine(continent);
}

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-Net