New Keyword: yield

The new yield keyword lets you return a value from an enumerated method.  You can use this wherever either you can't use a ref or out param, or when you can't use a return value.

The best time to use this is when you want to iterate through the return values of a method. Here's a rather convoluted example of when you could use this keyword.  The outmethod returns the Fibonnacci sequence and the OutMethod iterates through the results and formats them.  

   protected
static IEnumerable FibSeq(int maxValue)
   {
       float veryOld = 0;
       float old = 1;
       float fAbsValue = 0;
       yield old;
       while ((veryOld+old)<maxValue)
       {
          fAbsValue = veryOld + old;
          yield fAbsValue;
          veryOld = old;
          old = fAbsValue;
       }
    }

   protected static string OutMethod(int iterations)
   {
       StringBuilder sb = new StringBuilder();
       foreach (float fib in FibSeq(iterations))
       {
          sb.Append(fib); 
          sb.Append("\r\n");
       }
       return sb.ToString();
   }

5 Comments

Comments have been disabled for this content.