Yield – Enumeration candy

As we all know, I’m a little slow on the uptake.  This time I managed to miss a really great keyword in C#: yield.  The combination yield return is a lovely piece of C# candy that can be used to simplify a common function.  Consider the following section of code:

private IEnumerable<MyObject> FindObjectsWithThreeChildren(IEnumerable<MyObject> sourceList)
{
IList<MyObject> results = new List<MyObject>();
foreach (MyObject obj in sourceList)
{
if (obj.Children.Count == 3)
results.Add(obj);
}
return results;
}

We’ve all written something along those lines before.  Build a collection up based upon some predicate and then return it.  Now yes, this could actually be solved much more cleanly using a lambda expression with LINQ, but it could also be simplified using yield return.  The following is the same method written to take advantage of this new keyword:

private IEnumerable<MyObject> FindObjectsWithThreeChildren(IEnumerable<MyObject> sourceList)
{
IList<MyObject> results = new List<MyObject>();
foreach (MyObject obj in sourceList)
{
if (obj.Children.Count == 3)
results.Add(obj);
yield return obj;
}
return results;
}

The difference between yield return and a regular return is that with the yield keyword the method does not exit.  Instead the returned result is simply added into the collection to be returned.

For obvious reasons, this can only be used for methods that return enumerations.  It doesn’t do anything spectacular but it does make the source code a little bit cleaner and clearer, which can only be a good thing!

This entry was posted in Technology, Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *