245 words
1 minutes
Usage of yield in C#
yield in C# – Usage guide
When working with collections in C#, we often return lists or arrays. But what if you don’t want to load everything into memory at once?
That’s where yield comes in — one of the most powerful yet underused features in C#.
What is yield in C#?
The yield keyword allows you to return data one item at a time instead of returning the entire collection at once.
yield returnreturns the next itemyield breakstops iteration
It converts your method into an iterator that returns IEnumerable or IEnumerator.
Without yield?
public List<int> GetNumbers()
{
var list = new List<int>();
for (int i = 1; i <= 5; i++)
{
list.Add(i);
}
return list;
}- Entire list is created in memory
- No control over execution timing
With yield
public IEnumerable<int> GetNumbers()
{
for (int i = 1; i <= 5; i++)
{
yield return i;
}
}- No list created
- Better memory usage
- Lazy evaluation.
How yield works
- Method pauses at
yield return - Returns value to caller
- Next iteration → resumes from where it stopped
Example Execution
foreach (var num in GetNumbers())
{
Console.WriteLine(num);
}- Call method → hits
yield return 1 - Returns 1 → pauses
- Next loop → resumes → returns 2
- Continues…
yield break in C#
yield break is used to stop an iterator method immediately.
public IEnumerable<int> GetValidNumbers(List<int> numbers)
{
foreach (var num in numbers)
{
if (num < 0)
{
yield break; // stop if condition matches
}
yield return num;
}
}public IEnumerable<int> Example()
{
yield return 1;
yield return 2;
yield break;
// This will NEVER execute
yield return 3;
} Usage of yield in C#
https://crmte.ch/posts/yield/