Junior — Middle
Explain the principle of the yield operator in programming.
sobes.tech AI
Answer from AI
The yield operator in C# is used to create iterators, allowing methods to 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, it returns an element and pauses its execution, saving its current state. On the next request for an element, execution continues from where it was paused.
This is convenient for saving memory and implementing lazy evaluations.
Example:
IEnumerable<int> GetNumbers()
{
yield return 1;
yield return 2;
yield return 3;
}
foreach(var num in GetNumbers())
{
Console.WriteLine(num);
}
In this example, the numbers 1, 2, and 3 are returned one by one during each iteration of the loop.