c# (Csharp):- What is the use of Yield keyword in c# ?

Posted By on May 5, 2019



In this video we will try to understand what exactly is the use of Yield Keyword and in what scenario we should be using Yield Keyword let me summarize the use of Yield Keyword in one sentence Yield keyword help us to do custom iteration custom stateful for iteration over a collection that's statement is tough to understand right so let me simplifyd there are two basic uses of Yield keyword first when you want to do custom iteration and second one when you want to do stateful iteration so let me start with scenario number 1 custom iteration so here is the simple example i have you can see that i have a simple console application here and in this console application i have a list here called as MyList now this List is a numeric list that you can see that it has numbers like 1, 2, 3, 4, 5 and what i am doing is i have populated this list function called as FillValues and i am calling this FillValues as soon as static void main function runs and then what i am doing is i am just going and iterating through this My List over here so if i run this program here it will just go and display me 1, 2, 3, 4,5 so very simple program here it has my list in that i have added numbers and that number i am browsing through the static void main for now let's visualized this static void main as a caller a caller who actually call the My List and get the data and you will understand the importance why i am telling you to visualized static void main as a caller letter so we have a very simple application here and caller actually calls this My List and it is place the data 1, 2, 3, 4, 5 now let me go and complicate this situation little bit now let's say the caller wants to only displayed data which is greater than 3 so how do we go about doing it so logically what many developers do is they actually go and write function like this called as filter and in this filter go and create a temporary list like this called as temp then they go and browsed through the list and they say that if the value is grater than 3 then go and add into this temporary list and return this temporary list to the caller and then what i can do here is can go and call this filter function here and once a caller calls my filter function you can see that he has now browsed the value which is greater than 3 but now there is problem the problem is this temporary list it should be grate if you can write this filtering logic without using this temporary list and that's why exactly Yield will help us so the first thing what i will do here is i will get it of this list over here and i will get trade of this return over here and over here will just go and add Yield return i that's it so now if i do a ctr+F5 here you can see that it written me 4 and 5 which is nothing but these are numbers which are greater than 3 but now let me explain you internally what exactly happens when we used the Yield keyword internally the control moves from the caller to the source and from source to the caller 2 and 4 let me explain you step by step so in the first step the caller next called to the collection and it takes the first item and say is one greater than 3 no it is not grater than 3 it goes to the second item it's 2 grater than 3 no it is not third item now when it encounter the fourth item it's says is fourth grater than three yes 4 is grater than 3 and from here it's says Yield return the time it get's this keyword or this sentence Yield return the control moves back to the caller the caller then displays the same console and then re-enters look at this step 3 again returns into the function but this time remembers he has already browsed for elements it has to start from 5th elements and it again start the comparison is 5 grater than 3 yes it is again it goes back to the caller again soncole.writeline in other words when you used the Yield keyword the control moves back and 4th from the caller to the source from source to the caller now what i will do is let me go back in the code and let me show you this complete two and from moment by using the debug mode so let me put a debug point here in the Console.writeline and let me put a debug point in this Yield written over here or i will say in this if condition so let me start so the function enters into this filter and first value is 1 is 1 grater than 3 no second is 2 grater than 3 no is 3 grater than 3 no is 4 grater than 3 yes it is grater than 3 so from here is says Yield return now watch here now from here he will actually again go back to the static void main so here it is you can see now it has moved the control has moved back to the caller that is two static void main here display the value 4 here and again he re-enters can you see here again re-enter this function filter and it taking the 5th element is 5 grater than 3 yes it is again form here the control goes back to caller it pleased it and again re-enters and finally finishes so in this way when we used the Yield keyword the control moves from the caller to the source and from source back to the caller to and for so when we started this video we said that the use of Yield keyword to do stateful custom iteration so this was the simple example of custom iteration now let's try to see example of stateful iteration using Yield keyword so in order to understand stateful iteration let's take up the same collection that is 1 to 5 and now let's say that we want to display running total running total means as we move from element to element we would like to display the total of the elements we have browse till now means what for example we start with value 1 so the total is 1 removed to the second elements is 1 + 2 is 3 running total when we move to the 3rd elements it is 1 + 2 + 3 that is 6 when we move to the fourth elements 4+3+2+1 that is 10 so in way as you browse through the elements we want to display the running total now again here when we are displaying this running total we don't want to use temporary collection we want to keep our code simple so how can we do this by using the Yield keyword so here is the simple function i have created called as running Total and this running total uses the Yield keyword so you can see over here i have created temporary variable here called as running total and what this running total does is it has actually this variable actually accumulate value as it most through each element and whatever is current running total actually return back very easy now if you watch very closely what is means is that whenever the caller enter is running total again and again this value has to be preserve this value has to be preserved and Yield does that in other words if i go and browse this so if i say here RunningTotal let me put a debug point here let me move this at the top so that you can see the complete things in on row so here is our caller statistic void main it is now making a call to RunningTotal function and let me do F5 so there is start so you can see it has first re-enters first running total is 0 that is a right it takes the first element add's that element into to the RunningTotal so the RunningTotal Value is 1 moves again back to the caller displayed it again it re-enters watch this it has again re-enters this time it is taking the element 2 but look at the value of running total the value of Running total is 1 in other words it has preserved the value of RunningTotal so again so RunningTotal 1 plus the current element 2 that should be value 3 so that is 3 value again the control goes back to the caller the caller displayed it again it re-enters you can see it has preserved the previous value 3 and it is now going to add this 3 so that is 3+3 = 6 and in this way it goes and displays all the value on the console application all the running total console application there it is 1, 3, 6, 10 and 15 so in other words the other use of Yield keyword when you want to do statefull iteration so next time when someone asked you what is use of Yield keyword there are two basic use of Yield keyword one is when you want to do custom iteration without using temporary collection and second when you want to do statefull iteration and one point i also want to make here is basically when you go and browse using i enumerable i query-able those browsings are stateless in other words for example when we do for each through i enumerable it does not store state it does fast forward and moves but here when you used the Yield keyword you have the option of saving that's data as well I hope that videos was useful in this video i am trying to understand what is use of Yield keyword THANK YOU SO MUCH 🙂

Posted by Lewis Heart

This article has 22 comments

  1. Could someone please clarify: Why a static list property? You are calling it on the same class so.. It doesn't change how you invoke it.. I dont get it.

    Reply
  2. I've wathced another videos on "yield operator" and none of them was as understandable as yours. Many thanks!

    Reply
  3. Hi, for the first example, instead of temporary collection, shall I take the values greater than 3 using linq . Then why I could use yield in that place only. Kindly clarify it.

    Reply
  4. very nice explanation.. but will it not affect the performance ? what is the advantage of using it over other traditional ways ? please consider memory is not a costly thing now a days..

    Reply
  5. Provided great understanding about the yield keyword, but I have a question that

    is there any way where we can use it without foreach loop in caller function?

    Please Answer

    Reply
  6. I've a question, you can use the statment yield only when you return an IEnumerable or IEnumerable<T> collection?, and this only works when you use an iterator (foreach)?

    Reply
  7. Your explanations for "yield " keyword are more clear than the ones i saw on stack-overflow.
    Thanks dude.

    Reply
  8. Yield return is a way of returning the value to the enumerator do do whatever it wants to do with it, without aborting the current block's execution. If you notice, the enumerator method does not start from beginning but "continues" where it left off

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *