Yield return key-phrase that is used to return a value of the collection instead of returning the full list. It can be explained with example of watching a video. Yield is like streaming the video, while typical implementation is like downloading it. This phrase interacts with foreach loop, it iterates through collection of items, returns an item and gets called over and over again, but each time it resumes execution where it left off. It’s easier to read, and can have better performance than typical implementation.
In this example we have typical list and we iterate through it to find the results we are looking for, this is an example of Customized iteration through a collection.
static void Main(string[] args) { //We create en empty list List<int> NewList = new List<int>(); //We add few items NewList.Add(1); NewList.Add(2); NewList.Add(3); NewList.Add(4); NewList.Add(5); //Iterates through list, and displays the values foreach (int i in NewList) { Console.WriteLine(i); } }
You can find more about list in my post dedicated to it, here.
Now lets crate a method that find the values
static IList<int> FindGraterthan4(List<int> list) { var tempList = new List<int>(); foreach (var value in list) { if (value >= 4) tempList.Add(value); } return tempList; }
This way we create a new List(IList) we can iterate through to print results. We add this code to main method.
IList<int> TempList=FindGraterthan4(NewList); foreach (int i in TempList) { Console.WriteLine(i); }
New lets create the same thing with Yield Return
static IEnumerable<int> FindWithYR(List<int> list) { foreach (var value in list) { if (value >= 4) yield return value; } }
We can iterate through this with for each loop
foreach (int i in FindWithYR(NewList)) { Console.WriteLine(i); }
WE have the same result with less amount of code and better performance. This was just example of program that uses this phrase, In the future I’ll writhe article about the process that is happening in the background. In my next article I’ll cover the topic of IEnumerable interface. Stay Awesome!