[Non-WPF] I finally get it now... yield!
Thursday, April 9, 2009, 10:42 PM
Posted by Ruben Steins
While working through the excellend first chapter of the new APS.NET MVC book, I came across the yield keyword. Although I know I should get to terms with it, I was never able to really grasp what the benefits of using it were. Thank heavens
this guy has explained it so well on his blog. The MSDN examples pale in comparison to the clear and easy with-and-without yield examples Yason Young gives. From the comments on the posts, it's clear I am not alone in the yield-fearing world :)
Update: today I even contrived my own little test for yield:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<int> integers = new List<int>() { 3, 4, 8, 14, 24, 28, 52, 11, 33, 12,6 };
Program p = new Program();
TwoFilter filter2 = new TwoFilter();
ThreeFilter filter3 = new ThreeFilter();
int count = 0;
foreach (int i in filter3.Process(filter2.Process(integers)))
{
Console.WriteLine(i);
count++;
}
Console.ReadKey();
}
}
public interface IFilter<T>
{
IEnumerable<T> Process(IEnumerable<T> input);
}
public class TwoFilter : IFilter<int>
{
public IEnumerable<int> Process(IEnumerable<int> input)
{
foreach (int i in input)
{
if (i % 2 == 0)
{
Console.WriteLine("Called div 2 for " + i);
yield return i;
}
}
}
}
public class ThreeFilter : IFilter<int>
{
public IEnumerable<int> Process(IEnumerable<int> input)
{
foreach (int i in input)
{
if (i % 3 == 0)
{
Console.WriteLine("Called div 3 for " + i);
yield return i;
}
}
}
}
}
This uses some simply chaining to determine for each integer if its divisble by 2 and by 3. The nice thing is that the when you break out of the call loop (in Main) at any point, the Process method has not been called for any integer in the collection after that point, which could be a possible performance gain. Also it save you the trouble of creating temporary collections in each of the process methods to store the intermediate resultset in. All in all, pretty nifty, this yield.