Sobes.tech
Middle

What does the keyword yield mean? Why is it used?

sobes.tech AI

Answer from AI

The keyword yield in C# is used to create iterators — methods that return elements one at a time, without the need to create and return the entire collection at once. When a method with yield return is called, execution is paused, and it resumes from the same point on the next request for an element.

This allows efficient handling of large or potentially infinite sequences, saving memory and improving performance.

Example:

IEnumerable<int> GetNumbers()
{
    for (int i = 0; i < 5; i++)
    {
        yield return i; // return one element at a time
    }
}

// Usage:
foreach (var num in GetNumbers())
{
    Console.WriteLine(num);
}
What does the keyword yield mean? Why is it used? — C# - sobes.tech