Introduction to the Yield Statement

2 minute read

Introduction

The yield statement is a powerful construct in C# that allows you to create custom iterators. It allows you to define a method that returns a sequence of values, but instead of returning all of the values at once, it can return them one at a time as requested. This is particularly useful when working with large data sets or when you want to avoid loading all of the data into memory at once.

The yield statement works by suspending the method’s execution and returning a value to the caller. When the method is called again, it continues executing from where it left off, remembering its previous state.

Basic Usage of the Yield Statement

To use the yield statement, you need to define a method that returns an IEnumerable<T> or IEnumerator<T> object. Inside the method, you can use the yield return statement to return a value from the sequence.

Here’s an example of a method that returns a sequence of integers using the yield statement:

public static IEnumerable<int> GetNumbers()
{
    yield return 1;
    yield return 2;
    yield return 3;
    yield return 4;
    yield return 5;
}

In this example, the GetNumbers() method defines a sequence of integers by using five yield return statements. When this method is called, it will return an IEnumerable<int> object that represents the sequence of integers.

You can use a foreach loop to iterate over the sequence and retrieve each value:

foreach (int num in GetNumbers())
{
    Console.WriteLine(num);
}

This code will output the following:

1
2
3
4
5

Advanced Usage of the Yield Statement

The yield statement can also be used with the yield break statement to stop the sequence early. Here’s an example of a method that returns a sequence of integers up to a specified limit:

public static IEnumerable<int> GetNumbersUpTo(int limit)
{
    for (int i = 1; i <= limit; i++)
    {
        yield return i;
    }

    yield break;
}

In this example, the GetNumbersUpTo() method defines a sequence of integers up to a specified limit. It uses a for loop to generate the sequence, and then it uses the yield break statement to stop the sequence early.

You can call this method and pass in a limit to get the sequence:

foreach (int num in GetNumbersUpTo(3))
{
    Console.WriteLine(num);
}

This code will output the following:

1
2
3

Conclusion
The yield statement is a powerful feature in C# that allows you to define custom iterators that can return sequences of values. It can be used to create efficient and memory-friendly code when working with large data sets or when you need to retrieve data on-demand. By using the yield return and yield break statements, you can define complex sequences and stop them early when necessary.

Tags:

Categories:

Updated: