What is the use of c# “Yield” keyword ?






4.84/5 (104 votes)
In this blog we will go through 2 important uses of c# yield keyword.
- Customized iteration through a collection without creating a temporary collection.
- Stateful iteration.
Let’s try to understand what customized iteration means with an example. Consider the below code.
For now let’s visualize the “main()” method as a caller. So the caller i.e. “main()” method calls the list and displays the items inside it. Simple…till now ".
static List<int> MyList = new List<int>(); static void FillValues() { MyList.Add(1); MyList.Add(2); MyList.Add(3); MyList.Add(4); MyList.Add(5); } static void Main(string[] args) // Caller { FillValues(); // Fills the list with 5 values foreach (int i in MyList) // Browses through the list { Console.WriteLine(i); } Console.ReadLine(); }
static IEnumerable<int> FilterWithoutYield() { List<int> temp = new List<int>(); foreach (int i in MyList) { if (i > 3) { temp.Add(i); } } return temp; }
static IEnumerable<int> FilterWithYield() { foreach (int i in MyList) { if (i > 3) yield return i; } }
So for the above code following are details steps how the control will flow between caller and collection. You can also see the pictorial representation in the next diagram shown below.
- Step 1:- Caller calls the function to iterate for number’s greater than 3.
- Step 2:- Inside the function the for loop runs from 1 to 2 , from 2 to 3 until it encounters value greater than “3” i.e. “4”. As soon as the condition of value greater than 3 is met the “yield” keyword sends this data back to the caller.
- Step 3:- Caller displays the value on the console and re-enters the function for more data. This time when it reenters, it does not start from first. It remembers the state and starts from “5”. The iteration continues further as usual.
Scenario 2:- Stateful iteration<o:p>
In other words we will browse from 1 to 5 and as we browse we would keep adding the total in variable. So we start with “1” the running total is “1”, we move to value “2” the running total is previous value “1” plus current value “2” i.e. “3” and so on.
Below is the pictorial representation of the running total looks like.
In other words we would like to iterate through the collection and as we iterate would like to maintain running total state and return the value to the caller ( i.e. console application). So the function now becomes something as shown below. The “runningtotal” variable will have the old value every time the caller re-enters the function.
static IEnumerable<int> RunningTotal() { int runningtotal=0; foreach(int i in MyList) { runningtotal += i; yield return (runningtotal); } }
foreach (int i in RunningTotal()) { Console.WriteLine(i); } Console.ReadLine();
<o:p>
Video on use of C# “Yield” keyword
For Further reading do watch the below interview preparation videos and step by step video series.