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(" more (y/n)?");

        string more = Console.ReadLine();
        if (more.ToUpper() != "Y")

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s