0
0
CsharpConceptBeginner · 3 min read

What is yield keyword in C# and How It Works

The yield keyword in C# is used inside an iterator method to return each element one at a time, pausing the method's execution until the next element is requested. It simplifies creating enumerators without needing to build a collection manually.
⚙️

How It Works

Imagine you have a long list of items, but you want to give them out one by one instead of all at once. The yield keyword helps you do exactly that in C#. When a method uses yield return, it pauses after sending one item and waits until the next item is asked for before continuing.

This is like handing out pages of a book one at a time instead of giving the whole book at once. It saves memory and can make your program faster because it doesn’t have to prepare everything upfront.

💻

Example

This example shows a method that uses yield return to give numbers from 1 to 3 one by one.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static IEnumerable<int> GetNumbers()
    {
        yield return 1;
        yield return 2;
        yield return 3;
    }

    static void Main()
    {
        foreach (int number in GetNumbers())
        {
            Console.WriteLine(number);
        }
    }
}
Output
1 2 3
🎯

When to Use

Use yield when you want to create a sequence of values without building a full list in memory. It is helpful when working with large data sets or streams where you only need one item at a time.

For example, reading lines from a large file, generating infinite sequences, or filtering data on the fly are good cases for yield. It makes your code cleaner and more efficient.

Key Points

  • Yield pauses method execution and returns one item at a time.
  • It simplifies writing iterators without extra collections.
  • Improves memory use by generating items on demand.
  • Works only inside methods returning IEnumerable or IEnumerable<T>.

Key Takeaways

The yield keyword returns elements one at a time, pausing method execution between each.
Use yield to create efficient, lazy sequences without building full collections.
Yield works only in iterator methods returning IEnumerable or IEnumerable.
It helps handle large or infinite data streams cleanly and efficiently.