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 howIEnumerable
interface facilitate the use offoreach
statement to iterate through a set of data. We will then look how to implement our own collections that implementIEnumerable
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 implementIEnumerable
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 implementsIEnumerable
and see how we can have read only iteration over that usingforeach
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...