Using “yield” to enumerate endless sequence
Craig Andera in his blog post showed yet another Fibonacci algorithm, this one with “yeild” operator.
private IEnumerable Fibonacci()
{
yield return 0;
yield return 1;
int a = 0;
int b = 1;
while (true)
{
int temp = a + b;
a = b;
b = temp;
yield return b;
}
}
Now it's possible to fetch Fibonacci numbers in this manner:
static void Main(string[] args)
{
foreach (int a in Fibonacci())
{
Console.Write(a);
Console.Write(" more (y/n)?");
string more = Console.ReadLine();
if (more.ToUpper() != "Y")
break;
}
}
As you can see, code in Main procedure uses “foreach” statement, but the Fibonacci sequence is endless, so it can’t be populated in advance. Without “yield” we would have to create a temporary state variable (actually two: to store “a” and “b”) and pass them to a GetNextFibonacci that would produce a next number and return updated “a” and “b”. But with yield it’s possible to compute results on demand.