This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Yield keyword


In this article we are going to discuss about yield keyword with examples in C#.

The yield keyword in C# is used to simplify the implementation of iterator methods. An iterator method performs a custom iteration over a collection and can return each element one at a time. The yield keyword allows you to create a stateful iterator without the need to maintain the iteration state manually.

Usage of yield

The yield keyword can be used in two ways.

  1. yield return - This returns each element one at a time.
  2. yield break - This terminates the iteration.

Example of yield return

The yield return statement provides a value to the enumerator object and saves the current location in the code so that it can continue execution from this location the next time the enumerator is called.

Here is an example of using yield return in an iterator method.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        foreach (int number in GenerateNumbers(5))
        {
            Console.WriteLine(number);
        }
    }
    public static IEnumerable GenerateNumbers(int max)
    {
        for (int i = 1; i <= max; i++)
        {
            if (i > 3)
            {
                yield break;
            }
            yield return i;
        }
    }
}

Output

C# Yield Keyword

In this example

  • The GenerateNumbers method is an iterator that uses yield return to return each number.
  • When iterating over the collection using a foreach loop, the GenerateNumbers method yields each number one by one.

Prev Next