Implementing IEnumerable and IEnumerator on Your Custom Objects

From my technical blog:

Often you want to be able to enumerate through a collection of objects using the foreach statement in C#:

Using foreach in C#

foreach (Student student in myClass)      Console.WriteLine(student);

 

To be able to pull that off, myClass must implement IEnumerable:

 

IEnumerable Defined

Exposes the enumerator, which supports a simple iteration over a collection.

public IEnumerator GetEnumerator();

 

As is says above, IEnumerable just exposes another interface, called IEnumerator:

 

IEnumerator Defined

Supports a simple iteration over a collection.  Enumerators only allow reading the data in the collection. Enumerators cannot be used to modify the underlying collection.

public object Current;
public void Reset();
public bool MoveNext();

 

To see this in action, let's create an example by which we can iterate through a list of students in a class using the foreach statement in C#.

First, we need to create a Student Class as shown below.  At the minimum we want to override ToString() (Overriding System.Object.ToString() and IFormattable) so it says something meaningful and for kicks I decided to override Equals() and GetHashCode() (Object Identity vs. Object Equality - Overriding System.Object.Equals(Object obj)) only as an example.

Read more...

posted on Tuesday, March 08, 2005 12:30 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices