Junior — Middle
Can you give an example when the yield operator is used 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. This is convenient for saving memory and implementing lazy evaluations.
Example: a method that returns a sequence of numbers from 1 to 5:
IEnumerable<int> GetNumbers()
{
for (int i = 1; i <= 5; i++)
{
yield return i; // return one element at a time
}
}
// Usage:
foreach (var num in GetNumbers())
{
Console.WriteLine(num);
}
Here, yield return allows returning elements as they are requested, rather than all at once.