YIELD

This was a little function that I had forgot about in my development experiences.  In my never ending quest to cut code (using LINQ instead of iterations)  i had misplaced my knowledge around the use of YIELD.

So it was my goal to rediscover this lost knowledge.  The official definition is “Used in an iterator block to provide a value to the enumerator object or to signal an end of an iteration.”

Now with that mouthful there are rules:

  • Can only appear inside an iterator block, which may be used as a body of a method, operator, or accessor.
  • The body of a method, operator, or accessor has the following restrictions:
    • Unsafe blocks are not allowed.
    • Parameter can be ref or out
  • Cannot appear in an anonymous method.
  • When used with an expression, a YIELD return cannot appear in a catch block or try block have have one or more catch clauses.

// example from Microsoft
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, into exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}

static void Main()
{
foreach(int i in Power(2,8))
{
Console.Write(“{0} “, i);
}
} // output is 2 4 8 16 32 64 128 256 }

Leave a Reply