Home > Backend Development > C++ > How Does the C# `yield` Keyword Simplify Imperative Iteration?

How Does the C# `yield` Keyword Simplify Imperative Iteration?

Susan Sarandon
Release: 2025-01-27 17:31:10
Original
365 people have browsed it

How Does the C# `yield` Keyword Simplify Imperative Iteration?

Understanding C#'s yield Keyword for Efficient Iteration

Introduced in C# 2.0, the yield keyword significantly streamlines imperative iteration. Consider this example, illustrating its use in creating an IEnumerable<T>:

IEnumerable<object> FilteredList()
{
    foreach(object item in FullList)
    {
        if(IsItemInPartialList(item))
            yield return item;
    }
}
Copy after login

This function doesn't build a complete list in memory. Instead, it returns an iterator. Each time the foreach loop in the calling code requests the next item, the FilteredList() function resumes execution from where it left off, evaluating the next item and returning it only if the condition is met.

Let's examine a simpler example:

public void Consumer()
{
    foreach(int i in Integers())
    {
        Console.WriteLine(i);
    }
}

public IEnumerable<int> Integers()
{
    yield return 1;
    yield return 2;
    yield return 4;
    yield return 8;
    yield return 16;
    yield return 16777216;
}
Copy after login

Debugging this code reveals that Integers() doesn't execute fully at once. It executes only until it hits a yield return, returning a single value. The next iteration of the foreach loop in Consumer() causes Integers() to resume, continuing from the next yield return.

Key benefits of using yield:

  • Simplified Iteration: Avoids manual implementation of IEnumerable and IEnumerator, resulting in cleaner, more concise code.
  • Memory Efficiency: Values are generated on-demand, minimizing memory usage, especially beneficial when dealing with large datasets.
  • Improved Readability: The code's intent becomes clearer, particularly when handling iterative processes and data streaming. The logic for generating the sequence is directly embedded within the method.

The above is the detailed content of How Does the C# `yield` Keyword Simplify Imperative Iteration?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template