C# Yield Example: A Fun Way to Handle Iterators!
Ever been in a long queue at a restaurant? You order food, but instead of waiting for the entire order to be prepared, the waiter serves one dish at a time. That way, you can start eating while they cook the rest. 🍕🍔
That’s exactly how yield works in C#! Instead of returning everything at once, it sends data one item at a time, making things more efficient and faster.
What You Are Going to Learn in This Lesson?
✔️ What yield is and why it exists in C#
✔️ A real-world scenario to make it easy to understand
✔️ A C# Yield Example with code and output
✔️ How yield return and yield break work
What is Yield in C#?
The yield
statement simplifies iteration by allowing you to return items one at a time, instead of creating a whole collection.
Think of yield
as a lazy waiter who doesn’t rush to bring everything at once. Instead, he serves one item at a time only when requested.
There are two types of yield statements:
yield return
– Returns the next value in the sequence.yield break
– Stops the iteration when a condition is met.
Real-World Scenario: Generating Even Numbers
Let’s say we want to generate even numbers one by one instead of creating a list in memory. A normal method would return all numbers at once, but using yield
will make it more efficient.
C# Yield Example: Generating Even Numbers One by One
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Console.WriteLine("Even Numbers:");
foreach (int num in GetEvenNumbers(10))
{
Console.Write(num + " ");
}
}
static IEnumerable<int> GetEvenNumbers(int max)
{
for (int i = 2; i <= max; i += 2)
{
yield return i; // Returns one number at a time
}
}
}
Output:
Even Numbers:
2 4 6 8 10
Explanation:
1️⃣ The GetEvenNumbers()
method does not return a full list. Instead, it uses yield return
to return one even number at a time.
2️⃣ In Main()
, we use foreach
to fetch numbers one by one.
3️⃣ Instead of storing numbers in memory, yield return
saves resources by generating values only when needed.
Using yield break
to Stop Early
Let’s say we want to stop generating numbers when we reach 6
. We can use yield break
to exit early.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Console.WriteLine("Even Numbers:");
foreach (int num in GetEvenNumbers(10))
{
Console.Write(num + " ");
}
}
static IEnumerable<int> GetEvenNumbers(int max)
{
for (int i = 2; i <= max; i += 2)
{
if (i > 6)
yield break; // Stops when i is greater than 6
yield return i;
}
}
}
Output:
Even Numbers:
2 4 6
What Changed?
✅ The loop stops early when i > 6
.
✅ yield break
ends the iteration completely.
✅ It prevents unnecessary work when we don’t need more values.
Why Use Yield Instead of Lists?
Feature | Without yield ❌ | With yield ✅ |
---|---|---|
Memory Usage | Uses more memory | Uses less memory |
Performance | Slower for large data | Faster for large data |
Processing | Computes everything at once | Computes values only when needed |
💡 Use yield
when you want to process large collections efficiently without keeping everything in memory!
Conclusion
The yield
statement in C# makes iterators super efficient. Instead of returning all values at once, it returns them one by one, saving memory and improving performance. It’s like a waiter serving food dish by dish instead of bringing everything at once. 🍕
Now, go ahead and try it out yourself! And hey, if you have difficulty or a question, drop a comment. We will be happy to help you. 😊
Next What?
Now, what if you want to make decisions in your code? 🤔 Like, “If I have snacks, eat them. Otherwise, buy some!”
Well, that’s where Conditional Statements in C# come in! In the next chapter, you’ll learn how to make smart decisions in your programs using if, else, and switch statements. 🚀
Stay curious, keep learning, and see you in the next lesson! 😃