80. Yielding Fibonacci numbers

The following method yields Fibonacci numbers:

// Yield Fibonacci numbers.
private IEnumerable<long> FibonacciNumbers()
{
// Treat 0 and 1 separately.
yield return 0;
yield return 1;

// Calculate other values.
long fiboIMinus2 = 0;
long fiboIMinus1 = 1;
long fiboI = 0;
for (;;)
{
try
{
fiboI = checked(fiboIMinus2 + fiboIMinus1);
}
catch
{
yield break;
}

fiboIMinus2 = fiboIMinus1;
fiboIMinus1 = fiboI;
yield return fiboI;
}
}

First, the method yields the values 0 and 1. It then enters a loop where it uses previously calculated Fibonacci numbers to calculate the next number. The calculation uses the checked keyword to watch for integer overflow.

If no overflow occurs, the method uses yield return to return the new Fibonacci number. If the operation causes an overflow, the method uses yield break to stop generating values.

The program uses the following code snippet to display Fibonacci numbers:

int i = 1;
foreach (long fiboNumber in FibonacciNumbers())
fiboListBox.Items.Add(i++.ToString() + ": " + fiboNumber);

This code simply loops through the values yielded by the FibonacciNumbers method and displays them in the program's list box.

Download the YieldingFibonacciNumbers example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset