What is yield keyword in C# and How It Works
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.
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); } } }
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
IEnumerableorIEnumerable<T>.