Pages

Tuesday, April 21, 2009

C# and Yield operation

Are you confused how to use Yield in C#? MSDN says: "Yield is used in an iterator
block to provide a value to the enumerator object or to signal the end of iteration."
However, I found the concept of yield quite confusing, so I decided to make a code
sample how yield is used, so you can see how it operates and how it may benefit you.


    1 using System;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 
    5 namespace YieldTest
    6 {
    7   public class Tester
    8   {
    9     public static IEnumerable Power(int number, int exponent)
   10     {
   11       int counter = 0;
   12       int result = 1;
   13       while (counter++ <> 
   14       {
   15         result = result * number;
   16         yield return result;
   17       }
   18     }
   19 
   20     public static IEnumerable<string> GetEnumerator()
   21     {
   22       yield return "one";
   23       yield return "two";
   24       yield return "three";
   25     }
   26 
   27 
   28     static void Main(string[] args)
   29     {
   30       // Display powers of 2 up to the exponent 8:
   31       // 2 4 8 16 32 64 128 256
   32       foreach (int i in Power(2, 8))
   33       {
   34         Console.Write("{0} ", i);
   35       }
   36       Console.Write("\n");
   37 
   38       // Displays following:
   39       // one two three
   40       foreach(string s in GetEnumerator())
   41         Console.Write("{0} ", s);
   42 
   43       Console.ReadLine();
   44     }
   45   }
   46 }

Further reading in MSDN: yield (C# Reference)

No comments:

Post a Comment