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

"Introduction

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.

Background

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:

Post a Comment

NOTE: Anonymous Commenting has been turned off for a while... The comment spammers are just killing me...

ALL comments are moderated. I will review every comment before it will appear on the blog.

Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...

I reserve, and will use, the right to not approve ANY comment for ANY reason. I will not usually, but if it's off topic, spam (or even close to spam-like), inflammatory, mean, etc, etc, well... then...

Please see my comment policy for more information if you are interested.

Thanks,
Greg

PS. I am proactively moderating comments. Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...