245 words
1 minutes
Usage of yield in C#
2026-04-18

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 return returns the next item
  • yield break stops 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);
}
  1. Call method → hits yield return 1
  2. Returns 1 → pauses
  3. Next loop → resumes → returns 2
  4. 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/
Author
Anu Prakash S I
Published at
2026-04-18
License
CC BY-NC-SA 4.0