Yield Return in C#

Yield statement inside a method,operator or get accessor indicates them as an iterator

Defining yield to create iterator removes the explicit extra class required for creating enumerations.

How you can use yield?

  1. Yield return <expression>
  2. Yield break

Why you need to use “Yield” return?

You can use yield return to create an iterator which can be used to return each elements one by one.

Do and Don’t on Yield Keyword:

  • Return types always be one of the following
  1. IEnumerable
  2. IEnumerable<T>
  3. IEnumerator
  4. IEnumerator<T>
  • Yield declaration should not use “Out” or “ref ” keywords.

Here is a sample code to understand the yield return,

Explanation: As you can see in the above code, when the for loop code is getting executed, GetIds method should not return all the id’s at a single stretch. instead it calls the moveNext method of IEnumerable interface for each iteration.

To understand  it further follow these steps, place breakpoint inside the GetIds method like below and execute the code. you can able understand the yield keyword.

I will make one more separate post on yield keyword for exception handling and using yield with custom classes.

try out the below steps, and understand further.

Yield keyword Debugging

Yield keyword debugging

Yield debugging - Step 1

Yield debugging – Iteration

Yield debugging - Step 1

Yield debugging – Iteration 1 – Calling the GetIds method

Yield return - Control is given back to foreach loop

Yield return – Control is given back to foreach loop

Yield return - Iteration 2

Yield return – Iteration 2

Most of us do not pay much attention to understand very fine details about the several keywords in programming languages like c#, yes I agree, I  am also not an exceptional case here. In this post I am going to scribble about yield return and how it works?

Consider the below simple snippets,

Explanation

  1. GetUserNames method written with yield return keyword actually not returning any values when it is utilized in the foreach loop,
  2. It actually gives a promise to the caller.
  3. when the caller need the next value, GetUserNames method will give the next value.

Call to GetUserNames() does not execute the method, instead the call returns IEnumerable<string> to the caller.

What happens during the execution of the foreach?

MoveNext of IEnumerable interface getting called and it returns the next element and at the same time yield maintains the current element, so that during the next iteration yield will return the next element.

When will foreach terminate?   – foreach will terminate on the below two conditions,

  • when reaching the end of iterator method
  • when reaching yield break

Check out the wonderful article by kenneth truyers:

https://www.kenneth-truyers.net/2016/05/12/yield-return-in-c/

What you think about this concept, post your comments below to discuss further.

0 comments… add one

Leave a Comment