Saturday, 9 August 2025

yield in c# 
 Certainly! The yield keyword in C# is used to simplify the creation of iterators. 
It allows you to return each element of a collection one at a time, without the need for an explicit collection or temporary storage. 
Here's a breakdown of how it works: 
 yield return: 
 This statement is used to return each element one at a time. 
 When the yield return statement is reached, the current location in the code is remembered, and execution is paused until the next element is requested. Example:
IEnumerable<int> GetEvenNumbers(int max)
{
    for (int i = 0; i <= max; i += 2)
    {
        yield return i;
    }
}
yield break:
This statement is used to end the iteration early. It stops the iteration and exits the method. Example:
IEnumerable<int> GetNumbersUntilNegative(int[] numbers)
{
    foreach (int number in numbers)
    {
        if (number < 0)
        {
            yield break;
        }
        yield return number;
    }
}
Benefits: Simplifies Code: Reduces the need for explicit state management and temporary collections.

Lazy Evaluation: Elements are generated on-the-fly, which can improve performance and reduce memory usage. 
Usage: Commonly used in methods that return IEnumerable<int> or IEnumerator<int>. Can be used in both synchronous and asynchronous methods (with IAsyncEnumerable). 
 In summary, the yield keyword in C# provides a convenient way to create iterators, making your code cleaner and more efficient.
Share:

0 Comments:

Post a Comment