yield Statement in C#

With yield keyword, the control moves from the caller to source and from the source back to the caller to and fro.

yield statement can be used in two forms:

  1. yield return <expression>;
  2. yield break;
yield return statement returns each element at at time.

Yield return allows you to run custom iteration without temp collection.

Lets take an example to understand in more detail Function to return RandomNumbers using List.
  1. static IEnumerable < int > GetRandomNumbers(int count)  
  2. {  
  3.     Random rand = new Random();  
  4.     List < int > ints = new List < int > (count);  
  5.     for(int i = 0; i < count; i++)  
  6.     {  
  7.         ints.Add(rand.Next());  
  8.     }  
  9.     return ints;  
  10. }  
Same function using return yield without using any temp collection,
  1. using System;  
  2. using System.Collections.Generic;  
  3. namespace ConsoleApplication1  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             foreach(int i in GetRandomNumbers(10))  
  10.             Console.WriteLine(i);  
  11.         }  
  12.         static IEnumerable < int > GetRandomNumbers(int count)  
  13.         {  
  14.             Random rand = new Random();  
  15.             for(int i = 0; i < count; i++)  
  16.             {  
  17.                 yield  
  18.                 return rand.Next();  
  19.             }  
  20.         }  
  21.     }  
  22. }  
Output

Run

See, in the above examples, both are performing the same thing, but in the first example we are creating temp collection "list" but in the second example with yield there is no need create any temp collection

yield break statement is used to break the iteration. break statement is used to terminate the loop but yield break is used to return from the method.
  1. static void Main(string[] args)  
  2. {  
  3.     foreach(int i in GetRandomNumbers(10))  
  4.     Console.WriteLine(i);  
  5.     System.Threading.Thread.Sleep(5000);  
  6. }  
  7. static IEnumerable < int > GetRandomNumbers(int count)  
  8. {  
  9.     Random rand = new Random();  
  10.     for(int i = 0; i < count; i++)  
  11.     {  
  12.         yield  
  13.         return rand.Next();  
  14.         yield  
  15.         break;  
  16.     }  
  17. }  
Output

Output

Ebook Download
View all
Learn
View all