Thursday, December 31, 2015

yield Keyword Explained

When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class when you implement the IEnumerable and IEnumerator pattern for a custom collection type. The yield keyword was introduced in C# 2.0 (it is not currently available in VB.NET) and is useful for iteration. In iterator blocks it can be used to get the next value.
“Yield keyword helps us to do custom stateful iteration over .NET collections.” There are two scenarios where “yield” keyword is useful:
  • Customized iteration through a collection without creating a temporary collection
  • Stateful iteration
It is a contextual keyword used in iterator methods in C#. Basically, it has two use cases:
  • yield return obj; returns the next item in the sequence.
  • yield break; stops returning sequence elements (this happens automatically if control reaches the end of the iterator method body).
When you use the "yield return" keyphrase, .NET is wiring up a whole bunch of plumbing code for you, but for now you can pretend it's magic. When you start to loop in the calling code, this function actually gets called over and over again, but each time it resumes execution where it left off.
Typical Implementation
  1. Caller calls function
  2. Function executes and returns list
  3. Caller uses list
Yield Implementation
  1. Caller calls function
  2. Caller requests item
  3. Next item returned
  4. Goto step #2
Although the execution of the yield implementation is a little more complicated, what we end up with is an implementation that "pulls" items one at a time instead of having to build an entire list before returning to the client.
Example:
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 System.Collections.Generic.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
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.