Fibonacci numbers iterator with C# yield statements
Here’s a C# iterator for generating the sequence of Fibonacci numbers. It uses the yield return statement to pass back each number in turn. By default, the arithmetic addition won’t throw an exception when previous + current is greater than UInt64.MaxValue, so I’m using a checked expression to enable overflow checking.
public static IEnumerable<ulong> FibonacciNumbers()
{
yield return 0;
yield return 1;
ulong previous = 0, current = 1;
while (true)
{
ulong next = checked(previous + current);
yield return next;
previous = current;
current = next;
}
}
We can use the iterator with a foreach loop until it throws an OverflowException.
try
{
foreach (ulong i in FibonacciNumbers())
{
Console.WriteLine("{0:0,0}", i);
}
}
catch (OverflowException)
{
Console.WriteLine("Sorry, the next number is too big.");
}
about 5 months ago
Very cool yield keyword usage sample!!
about 5 months ago
It is not clear what version of .Net your code is targeting.
However, I dislike the checked addition and try/catch. It seems to be hack and also limits the maximum value that can be computer.
This could all be fixed by replacing the ulong with a BigInteger:
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger%28VS.100%29.aspx
about 5 months ago
Nice example. I actually liked the checked use, as you dont often see it and so good example of checked usage.
about 5 months ago
This is an excellent example of using the yield keyword, but I also think you could make this better by not relying on the OverflowException to control the flow. Using the “yield break” statement could help here:
public static IEnumerable FibonacciNumbers()
{
yield return 0;
yield return 1;
ulong previous = 0, current = 1;
while (previous <= (UInt64.MaxValue – current))
{
ulong next = previous + current;
yield return next;
previous = current;
current = next;
}
yield break;
}
This way, your while loop will end before the next number causes an overflow exception, and the yield break statement will signal the end of your enumeration.
Hope this helps. Cheers.