Thursday, October 11, 2012

An introduction to implementing IEnumerable and IEnumerable<T> and some yielding to yield too

CodeProject - A Beginner's Tutorial on Implementing IEnumerable and IEnumerable<T> interface and Understanding yield Keyword


In this article we will discuss about the IEnumerable interface. We will discuss how IEnumerable interface facilitate the use of foreach statement to iterate through a set of data. We will then look how to implement our own collections that implement IEnumerable interface. The use of yield keyword and Enumerating generic collections will also be discussed in this article.


Whenever we work with collection of objects, we might find ourselves in need to iterate the collection. The best way to iterate through a collection is by implementing the Iterator pattern. (refer: Understanding and Implementing the Iterator Pattern in C# and C++[^]). C# provides a very clean construct of foreach statement to iterate in a read only manner over a collection.

C# also provides us the possibility of using the same foreach construct and all the enumeration techniques on our custom collection objects by implementing the IEnumerable interface. So let us see how we can implement IEnumerable interface with our custom collection classes.

Using the code

Enumerating the Collection classes

Before starting the discussion let us see how we can use the Built-in classes and iterate over them. Lets start by looking into the ArrayList class that implements IEnumerable and see how we can have read only iteration over that using foreach statement.


I've had some conversations about creating custom IEnumerable/IEnumerable<T>/yield implementations and there were concerns that it might be "too much, and their heads might explode."

Next time I'll use this article as a soothing balm, teaching resource and concern killed (and anti-brain exploding device).  :)

No comments: