C# Yield

0

Category :

The following example shows the two forms of the yield statement.

1. Yield Break

You can use a yield break statement to end the iteration.

2. Yield Return expression

Return each iterator element one at a time. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

C# Example:

    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 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

Control flow:

1. Hits foreach
2. Enters Power method
3. Yield return result
4. Returns to outer foreach
5. Console write
6. Next loop of foreach re-enters Power method
7. Remembers previous value of "result"
8. And so oooooon......

Main Uses

Custom Iteration: No need for temp collection to store result-set that matches criteria.
Stateful Iteration: Keeping track of state during foreach

my thanks to:

https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
https://www.youtube.com/watch?v=4fju3xcm21M

0 comments:

Post a Comment