Yield Keyword in c#

Yield is one of the useful but less understood keyword available in C# Language. Yield provides two benefits –

  1. Avoids the use of memory for filtering a list.
  2. Remembers the state while iterating a list.

Let us start our discussion with a sample windows application. Our application will read a text file and filters the lines with the word “Cricket” and then prints them in the Console.


Here we have defined two classes to demonstrate the use of yield –

The first class is built with the logic without using yield statement. If we look into the code snippet of the class WithoutYield then we can find that, we are using a temporary list to store the lines having the keyword “Cricket”. This is a simple approach and hope everyone can understand. StearmReader will read the file line by line until it encounters null statement which determines the end of file. After reading each statement, “if condition” will check to see if the word “Cricket” exists. If it is there, it will add the line to the temporary list. Once the loop ends it will come out of the function after returning the list with two lines – 1st & 3rd.

If we write the control flow,

a) Call the ReadWithFilteredString method from main.
b) Read the file till it reaches EOF.
c) While reading filtering and populating the temporary list.
d) Return the temporary list to the caller main method.
e) Main method prints the entire list.

Now, consider the second approach of filtering with yield statement. Consider the class UseofYield. Here we are doing the same thing except the line “yield return line”. Notice that here we are not using any temporary storage for storing the filtered list. What yield statement does is that, it returns the result to the caller and remembers the state. Once in every execution of yield statement it returns to the caller, caller does its job and again comes back to read the line. So, if we write the control flow,

a) Call the ReadWithFilteredString method from main.
b) Read the line from the file if it is not null.
1. Check if it contains word “Cricket”. If it is there, then returns the line to main method. Else continue with the loop.
2. Main method prints the line when the control returns from yield.
3. Return to the called method and execute the loop from where it lefts off that is reading off file.
d) Return from the method to the caller main.

Frankly speaking if you run the above program with debugger, then you will have a clear understandings. Here the output is same for both the approach.

Hope reader understands the usability of yield statement.

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.