Often you want to be able to enumerate through a collection of objects using the foreach statement in C#:
To be able to pull that off, myClass must implement IEnumerable:
As is says above, IEnumerable just exposes another interface, called IEnumerator:
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.
We now need a custom class, called ClassList, that essentially holds the students. Forgetting IEnumerable for a moment, here is my barebones class. The class contains an ArrayList, called _students, which is populated with 3 students in its constructor. The list of students is private to ClassList and is currently not exposed outside of the class.
To support iteration using foreach on the class, I need to implement IEnumerable on ClassList. Since my students are in an ArrayList, and I know ArrayList implements IEnumerable, I am going to "cheat" and pass back the IEnumerator for _students:
Here is sample code you can run to see how it works:
If that is all the functionality you need, then passing the ArrayList's IEnumerator is the ticket. No sense creating your own IEnumerator if you don't have to.
However, we can create our own class, called ClassEnumerator, that implements IEnumerator and accomplishes the same thing as above. The class essentially just iterates through the _students arraylist using an index. Reset() sets the index back to -1. MoveNext() jumps ahead and returns a boolean as to whether we have hit the end. And, the Current property gets the current student.
Here is the entire code listing using our custom IEnumerator:
Now you can implement IEnumerable and IEnumerator on your custom objects.