In this article we will discuss about the
IEnumerableinterface. We will discuss how
IEnumerableinterface facilitate the use of
foreachstatement to iterate through a set of data. We will then look how to implement our own collections that implement
IEnumerableinterface. 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
foreachstatement to iterate in a read only manner over a collection.
C# also provides us the possibility of using the same
foreachconstruct and all the enumeration techniques on our custom collection objects by implementing the IEnumerable interface. So let us see how we can implement
IEnumerableinterface 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
ArrayListclass that implements
IEnumerableand see how we can have read only iteration over that using
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). :)