Use of Yield KeyWord in C#

Heard lot about “Yield” key word in C#.I has tried to understand the same and the power it produce in C#. Sharing the same knowledge /understanding with you.

Note: Yield is not .Net Feature rather it’s C# language feature.

To give you a quick picture of Yield just look at the very basic example of code that we generally use in our code without Yield:

  1. public List < string > FindEmployee(string name, List < string > lstCompleteList)  
  2. {  
  3.     List < string > lstEmp = new List < string > ();  
  4.     for (int i = 0; i < lstEmp.Count; i++) //You can use for each as well but I like For  
  5.     {  
  6.         if (lstCompleteList[i].ToString() == "YouDecide")  
  7.         {  
  8.             lstEmp.Add(lstCompleteList[i].ToString());  
  9.         }  
  10.     }  
  11.     return lstEmp;  
  12. }  

In the above example what we are trying to achieve is in case we have “YouDecide” name in our list, we are adding the same in new list and returning it back.

What is the ISSUE??

Here the issue is I am using a temporary list, which I can be avoided easily by using “Yield” key word. So our approach will be to avoid use of this temporary list. But How?

Look at the code below:

  1. public IEnumerable < string > FindEmployee(string name, List < string > lstCompleteList)  
  2. {  
  3.     foreach(var allname in lstCompleteList)  
  4.     {  
  5.         if (allname == name) yield  
  6.         return allname;  
  7.     }  
  8. }  

Now what I did in the above piece of code is, I am able to remove the temporary list by using Yield key world.

How Yield works:

When “yield” method get called in the method definition, it pause the current method execution. And when next time you call, it will continue it process with the last yield call.