Thursday, May 7, 2009

Yield return in C#

I was reading some of the sample code that comes with the Professional ASP.NET MVC 1.0 book and came across the yield return statement which I've seen before but never used.

It appears to be mostly syntactic sugar but may make the code more readable so I'm going to try and start using it to see if it improves the code smell.

Here is an example of how you might code something using a "classic" iterator:

        public static IEnumerable<string> FindStringsUsingClassic(string[] stringArray)
        {
            List<string> stringList = new List<string>();
            foreach (string s in stringArray)
            {
                if (s.StartsWith("f"))
                    stringList.Add(s);
            }
            return stringList;
        }

and here is the same code using yield return:

        private static IEnumerable<string> FindStringsUsingYield(string[] stringArray)
        {
            foreach (string s in stringArray)
            {
                if(s.StartsWith("f"))
                    yield return s;
            }
        }

Slightly less code but is it more readable and understandable? I don't know yet...

Those are contrived examples because if you're using C# 3.0 you would or should opt for the following:

        public static IEnumerable<string> FindStringsUsingLINQ(string[] stringArray)
        {
            return stringArray.Where(a => a.StartsWith("f"));
        }

 

2 comments:

  1. I think it is more than syntactic sugar, providing some kind of on-demand list processing magic.
    I used it recently to iterate through a very large list of member details. Rather than load them all into a huge list taking up loads of memory, then process each item in the list, yield meant I could call one row at a time from the db and process it with a very low memory footprint.

    ReplyDelete
  2. Thanks for the comment David. Until you wrote that I didn't realize that that was what was happening behind the scenes for yield return. I though that it was building the list and returning it and hence my comment about syntactic sugar.
    After some further investigation I see that you are correct and it is suitable for allowing the processing of lists of infinite size.
    Thanks for your comment - appreciated!

    ReplyDelete