What is the use of Yield keyword in C#? with example

The yield keyword will act as an iterator blocker and generate or return values.

The yield keyword in C# is used in iterator methods to create an iterator block. It allows you to define a sequence of values that can be iterated over without the need to store the entire sequence in memory at once. The yield keyword provides a convenient way to implement custom enumerators or iterate over large data sets lazily.

Here's an example to demonstrate the use of the yield keyword:

public IEnumerable<int> GetEvenNumbers(int start, int end) { for (int i = start; i <= end; i++) { if (i % 2 == 0) { yield return i; // Yielding the current value } } }

In this example, the GetEvenNumbers method returns an IEnumerable<int>, which represents a sequence of even numbers within the specified range. Instead of creating and returning a complete collection of even numbers, the method uses the yield keyword to generate each number on-the-fly.

The yield return statement is used inside the for loop to yield the current value of i. When the calling code iterates over the returned sequence, the method will be executed up to the point of the yield return statement. The yielded value is then returned to the calling code, and the method's state is saved. Subsequent iterations continue from where they left off, generating and returning the next value in the sequence.

Example usage:

foreach (int number in GetEvenNumbers(1, 10)) { Console.WriteLine(number); }

Output:

2 4 6 8 10

In this example, the foreach loop iterates over the sequence of even numbers returned by the GetEvenNumbers method. The numbers are generated on-demand as the loop iterates, rather than generating the entire sequence upfront. This lazy evaluation improves performance and memory efficiency, especially when working with large data sets or infinite sequences.

In summary, the yield keyword in C# is used to create iterator blocks and generate sequences of values lazily. It allows for more efficient memory usage and enables the implementation of custom iterators or generators.

 

Post a Comment

Previous Post Next Post