yield Keyword in c# — Stateful Iteration

Prerna Kaushik
4 min readDec 3, 2018

Yield is a contextual keyword. To make is more relatable at the start itself in simple word is it is a custom iterator that maintains state.

Ok! Too much of information in the start itself! so let’s start slow and understand what is yield? Why yield? How does it differ from IEnummerator?

I was introduced to this keyword recently during a technical discussion with one the experienced and highly knowledgeable person working as Manager Connect Clients. Being honest, I had no idea about this and He helped me through the code and explained a bit about how it works and how it saves our coding efforts. So, let’s jump right into the discussion below and understand this context better. In case, you find any changes required, additions or modification, please comment below with suggestions and corrections. Would be really helpful.

What is yield Keyword?

I will try and define this is an easy yet to the point words. Yield is a keyword in c# that allows you to take control back to calling method for each iteration and get control back on loop at the same position from where you left the loop.

In two simple lines you can say :

  • A keyword that allows you to get custom iteration without extra variables.
  • A keyword that gives you stateful iteration.

Now, lets understand these two statements and the answer to question — Why yield? and How does yield differ from IEnummerator?

Let’s start with an example,

Question : Write a program to add few int items in a list and display them on console

This is a simple question that all of us can answer.

Now, let’s suppose there is some change where we want that only the elements of list greater than 10 should be displayed. Now, let’s examine carefully. Below is the answer that most us with answer.

But, do we actually require an extra list or an temporary variable. yield comes handy in these situations it helps you with “Custom Iteration” without any extra variable.

Have a look at code section below :

Now, you know the answer to Why yield?

“return yield” send the control to the calling method directly. so in example above instead of creating a new list, adding filtered values to it and then printing it. we used yield which checked the condition while iterating over same list, when condition was satisfied it went to calling method to execute functionality and then came back to same list without changing it.

This example also shows you a glimpse of “Stateful iteration”. Now to completely understand the meaning of stateful in terms of iteration lets look at the example given below.

Now, suppose we want to display the list items with a ‘,’ in between. which means if list is — 1,2,3,4,5 we want to display it as ‘1’, ‘1,2’, ‘1,2,3’, ‘1,2,3,4’ ,’1,2,3,4,5'.

Now if i go with yield in this case the code would be something i attached below.

Now, you know it is a stateful iteration. In above example when loop started and first element was passed to ConcatenatedValue() it initialized the ConcatenatedString variable and added its value so concatenatedString value became as “100”. Now it went back to calling part and printed value :

100

Now, it came back for 2nd variable in the loop, at this point if you debug you will see that it maintains the state of variable ConcatenatedString till the end of loop so here the value of variable remains “100”. Now it adds second variable to it. making output as :

100

100,10

and so on.

FEW POINTS THAT MIGHT HELP

To break out of loop while using yield you can use — yield break;

A yield return statement can’t be placed inside a try catch block. You may do your functionality inside try throw exception from catch and then write your return return at the end.

You can place yield statement in try in case you are not handling catch and using try-finally.

On the other hand, you can’t place yield break in finally, but can exist in try-catch block.

Conclusion:

in simple words you can say yield gives you two major plus points of — Custom Iteration and Stateful Iteration.

I am very new to this Keyword, i tried to sum up all the knowledge i gained by reading MSDN documents, videos on internet and minor implementation in code. In case you find any suggestions, improvements or add on to the article please do comment below. It would come to me a great source of learning.

Thank you!

--

--