Click here to Skip to main content
15,867,785 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
4.84/5 (115 votes)
7 Apr 2014CPOL3 min read 248.3K   99   33
In this blog we will go through 2 important uses of c# yield keyword.
“Yield keyword helps us to do custom stateful iteration over .NET collections.”
 
There are two scenarios where “yield” keyword is useful:-
 
 
  • Customized iteration through a collection without creating a temporary collection.
  • Stateful iteration.
 
 
Scenario 1:- Customized iteration through a collection<o:p>
 

Let’s try to understand what customized iteration means with an example. Consider the below code.

 
Let say we have a simple list called as “MyList” which has collection of 5 continuous numeric values 1,2,3,4 and 5. This list is browsed/iterated from console application from within static void main method.
 

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 Wink | <img src= ".

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();
}
Image 2
 
 
 
Now let me complicate this situation let’s say the caller only wants values greater than “3” from the collection. So the obvious thing as a c# developer we will do is create a function as shown below. This function will have temporary collection. In this temporary collection we will first add values which are greater than “3” and return the same to the caller. The caller can then iterate through this collection.
static IEnumerable<int> FilterWithoutYield()

{
            List<int> temp = new List<int>();
            foreach (int i in MyList)
            {
                if (i > 3)
                {
                    temp.Add(i);
                }
            }
            return temp;
} 

 

 
 
Image 3
 
 
 
Now the above approach is fine but it would be great if we would get rid of the collection, so that our code becomes simple. This where “yield” keyword comes to help. Below is a simple code how we have used yield.
 
“Yield” keyword will return back the control to the caller, the caller will do his work and re-enter the function from where he had left and continue iteration from that point onwards. In other words “yield” keyword moves control of the program to and fro between caller and the collection.
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.
 

Image 4

 

 

 

 

 

 

 

Scenario 2:- Stateful iteration<o:p>

Now let us add more complications to the above scenario. Let’s say we want to display running total of the above collection. What do I mean?.

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.

 
Image 5


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);
                 
             }
         }
 
Below goes the caller code and output.
foreach (int i in RunningTotal())

            {
                Console.WriteLine(i);
            } 
            Console.ReadLine(); 

<o:p>

 
 
Image 6
 
 

Video on use of C# “Yield” keyword

Image 7

For Further reading do watch  the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
QuestionBest Explanation Pin
Shabana Parveen21-Apr-18 19:14
professionalShabana Parveen21-Apr-18 19:14 
PraiseSimple explanation Pin
vamsi.welcome1-Apr-17 9:39
vamsi.welcome1-Apr-17 9:39 
PraiseGreat article Pin
Jyotendra922-Oct-16 19:28
Jyotendra922-Oct-16 19:28 
QuestionComment Pin
Rizwan Gazi29-Mar-16 20:16
Rizwan Gazi29-Mar-16 20:16 
GeneralGood Explanation Pin
Alireza_136227-Mar-16 10:41
Alireza_136227-Mar-16 10:41 
GeneralMy vote of 5 Pin
M Rayhan21-Mar-16 1:00
M Rayhan21-Mar-16 1:00 
PraiseNice article Pin
kotra.ramakrishna2-Dec-15 3:27
professionalkotra.ramakrishna2-Dec-15 3:27 
QuestionGreat explanation Pin
HankMooody12-Aug-15 0:14
HankMooody12-Aug-15 0:14 
GeneralMy vote of 5 Pin
NoumanUllah Siddiqui1-Aug-15 15:22
NoumanUllah Siddiqui1-Aug-15 15:22 
Questionnice explanation Pin
User 418025428-Jul-15 9:06
User 418025428-Jul-15 9:06 
GeneralExcellent Pin
Rajneesh Rai29-Dec-14 21:11
Rajneesh Rai29-Dec-14 21:11 
QuestionHow about this version of FilterWithoutYield()? There is no temp List. Pin
Member 107284215-Nov-14 15:48
Member 107284215-Nov-14 15:48 
AnswerRe: How about this version of FilterWithoutYield()? There is no temp List. Pin
bbqchickenrobot19-Dec-14 21:02
bbqchickenrobot19-Dec-14 21:02 
GeneralRe: How about this version of FilterWithoutYield()? There is no temp List. Pin
nirman b doshi29-Jan-18 1:36
nirman b doshi29-Jan-18 1:36 
AnswerRe: How about this version of FilterWithoutYield()? There is no temp List. Pin
Sushil Mate25-Feb-15 22:40
Sushil Mate25-Feb-15 22:40 
Questionbest explanation Pin
usrikanthvarma1-Oct-14 17:38
usrikanthvarma1-Oct-14 17:38 
GeneralBest explanation Pin
Saily11-Aug-14 6:50
Saily11-Aug-14 6:50 
GeneralMy vote of 5 Pin
ognyandim25-Apr-14 4:13
ognyandim25-Apr-14 4:13 
GeneralMy vote of 3 Pin
_Noctis_15-Apr-14 11:06
professional_Noctis_15-Apr-14 11:06 
QuestionThank's ... Pin
zepp6614-Apr-14 22:04
professionalzepp6614-Apr-14 22:04 
GeneralMy vote of 3 Pin
coder_help13-Apr-14 19:53
coder_help13-Apr-14 19:53 
GeneralMy vote of 2 Pin
paulsasik9-Apr-14 8:50
professionalpaulsasik9-Apr-14 8:50 
GeneralRe: My vote of 2 Pin
Shivprasad koirala13-Apr-14 20:22
Shivprasad koirala13-Apr-14 20:22 
Questionnice blog Pin
Suk@nta8-Apr-14 10:20
Suk@nta8-Apr-14 10:20 
GeneralMy vote of 4 Pin
jfriedman11-Apr-13 20:49
jfriedman11-Apr-13 20:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.