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"));
}