Yield Keyword in C#

Introduction

 
In this blog, we are discussing the use of the yield keyword with a simple program.
 
What is the use of the Yield Keyword?
 
The yield keyword helps us to do custom iteration over the collection. There are two types of iteration.
  1. Custom Iteration
  2. Stateful Iteration 
Let's discuss this with a simple program. Please check the below program where we have a simple example for demonstrating usage of the yield keyword.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace yieldkeyword  
  8. {  
  9.    public  class Program  
  10.     {  
  11.        static  List<int> mylist = new List<int>();  
  12.        static void addvalues()  
  13.         {  
  14.             mylist.Add(1);  
  15.             mylist.Add(2);  
  16.             mylist.Add(3);  
  17.             mylist.Add(4);  
  18.             mylist.Add(5);  
  19.         }  
  20.         static void Main(string[] args)  
  21.         {  
  22.   
  23.             addvalues();  
  24.             foreach(int i in mylist)  
  25.             {  
  26.                 Console.WriteLine(i);  
  27.             }  
  28.             Console.ReadLine();  
  29.         }  
  30.     }  
  31. }  
In the above program, I am filling the values to mylist collection by calling the addvalues method in the main method and by using foreach or iteration for displaying the values. Please check the below snapshot:
 
 
 
Let's visualize the execution of the above program. Please check the below snapshot.
 
 
 
The static void main method is a caller who actually calls the mylist method.
 
Let's complicate the requirement and display values only greater than 2. Usually, developers will go for the temporary list. In this type of situation, instead of the temporary list, we can use the yield keyword. Please check the below program.
  1. foreach(int i in mylist)  
  2.             {  
  3.                 if (i > 3)  
  4.                 {  
  5.                     yield return i;   
  6.                 }  
  7.                 
  8.             }  
 Let's visualize the execution of the above program. Please check the below snapshot.
 
 
 
Internally, the controller moves to the caller to the source and source to the caller.
Please check the below snapshot for output.
 
 
 

Summary

  
In this blog, we discussed the yield keyword usage with a simple program. I hope that you find it helpful.
Eat->Code->Sleep->Repeat.
Next Recommended Reading Enumerators and Yield in C#