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:
- public List < string > FindEmployee(string name, List < string > lstCompleteList)
- {
- List < string > lstEmp = new List < string > ();
- for (int i = 0; i < lstEmp.Count; i++)
- {
- if (lstCompleteList[i].ToString() == "YouDecide")
- {
- lstEmp.Add(lstCompleteList[i].ToString());
- }
- }
- return lstEmp;
- }
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:
- public IEnumerable < string > FindEmployee(string name, List < string > lstCompleteList)
- {
- foreach(var allname in lstCompleteList)
- {
- if (allname == name) yield
- return allname;
- }
- }
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.