The Journey of yield vs return in C#

Osama HaiDer
3 min readJan 8, 2024

--

If you’ve ever been curious about C# and got a bit confused about the words “yield” and “return,” you’re in good company. In this blog post, we’ll break down these two terms and see how they work by looking at a straightforward example of adding numbers to a list.

Setting the Stage

Before we dive into the example, let’s quickly understand the roles of yield and return in C#.

return:

The return keyword is your trusty companion when you want to conclude a method and hand back a value. It's like saying, "Here's what you asked for; I'm done."

yield:

On the other hand, yieldis like a magic tool that helps create iterators. Iterators are like a way to go through a bunch of things one by one. With yield you can pause and continue going through these things, which is really helpful when you’re working with sequences of data.

The traditional return:

Now, let’s embark on a journey with a simple example. We want a method that adds numbers to a list and prints a message each time a number is added. We’ll implement this first using return and then with the enchanting yield.

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
// Using GetNumbersWithReturn
Console.WriteLine("Using GetNumbersWithReturn:");
List<int> numbersList = GetNumbersWithReturn();
foreach (int num in numbersList)
{
Console.WriteLine(num);
}

Console.ReadLine(); // To keep the console window open
}

public static List<int> GetNumbersWithReturn()
{
List<int> numbers = new List<int>();
numbers.Add(1);
Console.WriteLine("Number 1 Added");

numbers.Add(2);
Console.WriteLine("Number 2 Added");

numbers.Add(3);
Console.WriteLine("Number 3 Added");

return numbers;
}
}

Output:

Using GetNumbersWithReturn:
Number 1 Added
Number 2 Added
Number 3 Added
1
2
3

As you can see, the GetNumbersWithReturn method adds numbers to a list and prints a message for each addition. The list is then returned and iterated over in the Main method.

The yield magic:

Now, let’s reimagine this tale with the magical touch of yield.

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Using GetNumbersWithYield
Console.WriteLine("Using GetNumbersWithYield:");
foreach (int num in GetNumbersWithYield())
{
Console.WriteLine(num);
}
Console.ReadLine(); // To keep the console window open
}
public static IEnumerable<int> GetNumbersWithYield()
{
yield return 1;
Console.WriteLine("Number 1 Yielded");

yield return 2;
Console.WriteLine("Number 2 Yielded");

yield return 3;
Console.WriteLine("Number 3 Yielded");
}
}

Output:

Using GetNumbersWithYield:
Number 1 Yielded
1
Number 2 Yielded
2
Number 3 Yielded
3

In this enchanting version, the GetNumbersWithYield method uses yield return to create an iterator. As each number is yielded, a corresponding message is printed. The magic happens when the foreach loop in the Main method iterates over the numbers one by one.

Performance of yield vs. Normal return

Traditional return:

When we use the traditional return statement, the method calculates all the values at once and hands them back as a complete result. This approach can be quick for small datasets, but it may consume a lot of memory, especially with larger collections.

yield Magic:

On the other hand, the magic of yield shines in scenarios where we don't need all the values immediately. Instead of computing everything upfront, yield generates and provides each value one at a time. This lazy evaluation reduces memory usage and can significantly improve performance, especially when dealing with extensive or infinite sequences.

Conclusion: Choosing the Right Spell

When to use each depends on your needs. If you want the entire result at once, return is your reliable spell. If you prefer a magical, lazy approach that yields results on demand, then yield is your enchanting choice.

In your coding adventures, consider the nature of your data and the iteration requirements. Whether you choose the straightforward path or opt for a touch of magic, may your code be both efficient and delightful!

Join the Discussion

Connect with me on LinkedIn for further insights and collaboration opportunities. Your feedback and ideas are highly appreciated!

Happy coding!

--

--

Osama HaiDer
Osama HaiDer

Written by Osama HaiDer

SSE at TEO International | .Net | Azure | AWS | Web APIs | C#

No responses yet