C# Interview Question #88
What is the yield keyword in C#?
Advanced C# Language Features Mid-Level Intermediate
Quick Interview Answer
The yield keyword is used to implement an iterator without manually building and returning the entire collection.
Detailed Explanation
The yield keyword is used to implement an iterator without manually building and returning the entire collection.
yield return produces one element at a time, and execution is suspended until the caller requests the next element. yield break ends the iteration.
This enables deferred and streaming-style enumeration and can reduce memory usage when the complete result does not need to be created in advance.
Code Example
public IEnumerable<int> GetEvenNumbers(int max)
{
for (int i = 0; i <= max; i++)
{
if (i % 2 == 0)
yield return i;
}
}