Friday, May 4, 2012

How to use Yield Return

In a yield return statement, expression is evaluated and returned as a value to the enumerator object; expression has to be implicitly convertible to the yield type of the iterator.

The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:
  • Unsafe blocks are not allowed.
  • Parameters to the method, operator, or accessor cannot be ref or out.
  • A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.
  • A yield break statement may be located in a try block or a catch block but not a finally block.
A yield statement cannot appear in an anonymous method

Sample

 namespace Yield_Return  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       // Compute two with the exponent of 30.  
       foreach (int value in ComputePower(2, 30))  
       {  
         Console.Write(value);  
         Console.Write(" ");  
       }  
       Console.WriteLine();  
       Console.ReadLine();  
     }  
     public static IEnumerable<int> ComputePower(int number, int exponent)  
     {  
       int exponentNum = 0;  
       int numberResult = 1;  
       //  
       // Continue loop until the exponent count is reached.  
       //  
       while (exponentNum < exponent)  
       {  
         //  
         // Multiply the result.  
         //  
         numberResult *= number;  
         exponentNum++;  
         //  
         // Return the result with yield.  
         //  
         yield return numberResult;  
       }  
     }  
   }  
   public class Yield {  
     public IEnumerable<string> GetMergedCount(string[] count, string[] count1)  
     {  
       foreach (string item in count)  
       {  
         string counts = string.Empty;  
         foreach (string item1 in count1)  
         {  
           if (item1.Equals(item))  
           {  
             counts =counts+ item1.ToString();  
             yield return counts;  
           }  
         }  
       }  
     }  
   }  
 }  

No comments:

Post a Comment