What is the yield keyword used for in C#?

In C#, the yield keyword is used in an iterator block to create an iterator, which is a construct that enables the easy implementation of custom enumerators. The yield keyword is specifically used in combination with the yield return and yield break statements to define the behavior of the iterator.

Here’s how the yield keyword is used in C#:

  1. yield return Statement:
    • Within an iterator block, the yield return statement is used to return a value from the iterator and suspend the execution temporarily.
    • The next time the iterator is called, execution resumes from where it left off after the yield return statement.
  2. yield break Statement:
    • The yield break statement is used to end the iteration and exit the iterator block.
    • It is typically used to signal that there are no more elements to yield.

Here’s an example to illustrate the usage of the yield keyword:

public IEnumerable<int> GetEvenNumbers()
{
    for (int i = 0; i < 10; i++)
    {
        if (i % 2 == 0)
        {
            yield return i;
        }
    }
}

// Usage:
foreach (int number in GetEvenNumbers())
{
    Console.WriteLine(number);
}

In this example, the GetEvenNumbers method is defined as an iterator block by using the yield keyword. It returns an IEnumerable<int> object that can be iterated over. Within the loop, the yield return statement is used to yield even numbers one at a time. When the loop encounters the yield return statement, it returns the current value and temporarily suspends execution. The next time the iterator is called, it resumes execution from where it left off, continuing the loop until it is completed.

The yield keyword provides a convenient way to implement custom enumerators without explicitly creating a separate class or manually managing the state of the iteration. It simplifies the implementation of iterators by handling the complex logic of state management and iteration for you.

Iterators using the yield keyword are useful when working with large or dynamically generated collections of data, as they provide a memory-efficient and on-demand approach to retrieving elements one at a time.

error: Content is protected !!