Using yield keyword to write better code in c#

Amr elshaer
3 min readFeb 27, 2022

--

In this story, I use a simple example to demonstrate our goal, I have a list of students and want to get the teenage Students.

I improve GetTeenAgerStudent() method to be extension method

be if I want to take the first two students not all, like this.

the result will be

great, it works as expected, but I get some questions if he first processes all students and then takes our first two students, our process until reach two students?

So, I add some code to trace this. modified extension method

The result

the answer is it process all students and then takes the first two students 🤢but this is not good for performance, If I deal with huge data this will be expensive.

to improve our code by using yield return, If you don’t know yield you can see doc

what is the result?

we see that the name is displayed twice behind each other, not amr and then Johan this is because yield return the statement returns each element one at a time.

the second thing we note is that not all data processes then take the first two students, but processes until reach 2 students, and another thing we get ride of temp field (IList<Student> students) to write better code.

one thing important for yield is help to achieve Deferred Execution

Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. It greatly improves performance by avoiding unnecessary execution.

If we run this code without foreach or .ToList this will not print anything

the code is not executed until foreach or .tolist at the end of the line, but without yield return, it will execute immediately although I didn’t consume teenAgerStds.

In the end, I know I can use where instead of all this and the code will be like this

but, I want to show how where it works and to understand yield to build better code.

--

--