C# Yield Return in IEnumerable

Stop worrying about all the extra collections and sub-collections you have to create when you search a collection for those objects fitting certain criteria. We all do it on a daily basis, we create methods to search collections for all objects which fit certain criteria and we copy the located objects to a new temporary holder collection. Once the method has finished searching the entire source collection it then returns the temporary holder collection as its result.

Example Code:
private List GetPeopleWithSameName(string name, List srcPeople)
{
    List tempList = new List();
    foreach(Person p in srcPeople)
    {
        if(p.FirstName.Equals(name))
            tempList.Add(p);
    }
    return tempList;
}

What if we didn’t have to worry about creating and maintaining those temporary holder collections in our methods? What if we could get one of those located object at a time, at the very time it is found and pass it off for processing without waiting for the entire collection to be searched? Thanks to the new Yield Return construct we can.

How it works: When the .Net compiler sees the Yield Return construct it creates a nested private class which implements the IEnumerable, IEnumerator and IDisposable interfaces. This dynamically created class is pretty much a utility that maintains the state of your enumeration through the collection you are searching. Because this class tracks the state of the enumeration the method you created can return each object it finds which matches the criteria you set, and it returns it at the moment it finds it. Now we can compress our method as shown below.

Example Code:
private List GetPeopleWithSameName(string name, List srcPeople)
{
    foreach(Person p in srcPeople)
        if(p.FirstName.Equals(name))
            yield return p;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s