March 26, 2009

Using 'yield' in C#

One nice feature of C# which I wasn't aware of for a long time (sometimes it would pay off to have read a proper C# book cover to cover....) is the yield keyword. It is a very nice way to implement enumerators.

Lets look at an example, which prints out the well known Fibonacci numbers up to 1000:


class Fibonacci
{
public static IEnumerable<int> GetUpTo(int max)
{
int a = 0;
int b = 1;

yield return a;
yield return b;

while (true)
{
int next = a + b;

if (next >= max)
yield break;

yield return next;
a = b;
b = next;
}
}

static void Main()
{
foreach (var x in Fibonacci.GetUpTo(1000))
{
Console.WriteLine(x);
}
}
}


yield can be used only as yield return (which adds a new item to the enumeration) and yield break, which stops the enumeration.

The example could also be written without yield break which makes it a bit nicer:


public static IEnumerable<int> GetUpTo(int max)
{
int a = 0;
int b = 1;

yield return a;

while (b < max)
{
yield return b;

int next = a + b;
a = b;
b = next;
}
}

Without yield one would need to write a class to implement the iterator and maintain the loop state from one call to the next. Much nicer with yield. Okay, for this example you wouldn't really need an iterator in the first place but I hope the point came across...
blog comments powered by Disqus