yield keyword in C#

csharp comments

yield keyword has been added to C# long time ago but I never made a habit of using it. Basically what it does is create an iterator and allows you to return an IEnumerable one item at a time.

For example in the example below (from MSDN) Power returns a single int. But the return type of the method is IEnumerable. This is because of the _yield_ usage. Every time it's called it returns the next value it calculates.

public class PowersOf2
    static void Main()
        // Display powers of 2 up to the exponent of 8: 
        foreach (int i in Power(2, 8))
            Console.Write("{0} ", i);

    public static IEnumerable<int> Power(int number, int exponent)
        int result = 1;

        for (int i = 0; i < exponent; i++)
            result = result * number;
            yield return result;

    // Output: 2 4 8 16 32 64 128 256

I developed a small Fibonacci calculator using yield.

Notice the first two occurences:

yield return f0;
yield return f1;

When it’s first called it returns f0 (0) and on second call it omits that return and returns f1 (1) and on subsequent calls it loops until the desired numbers and returns the series up until that point.

And the output looks like this:

Fibonacci console output


  • [MSDN Reference] (http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx)