Creating Iterators Using Yield

suggest change

Iterators produce enumerators. In C#, enumerators are produced by defining methods, properties or indexers that contain yield statements.

Most methods will return control to their caller through normal return statements, which disposes all state local to that method. In contrast, methods that use yield statements allow them to return multiple values to the caller on request while preserving local state in-between returning those values. These returned values constitute a sequence. There are two types of yield statements used within iterators:

This example below demonstrates an iterator method that can be used to generate the Fibonacci sequence:

IEnumerable<int> Fibonacci(int count)
{
    int prev = 1;
    int curr = 1;
    
    for (int i = 0; i < count; i++)
    {
        yield return prev;
        int temp = prev + curr;
        prev = curr;
        curr = temp;
    }
}

This iterator can then be used to produce an enumerator of the Fibonacci sequence that can be consumed by a calling method. The code below demonstrates how the first ten terms within the Fibonacci sequence can be enumerated:

void Main()
{
    foreach (int term in Fibonacci(10))
    {
        Console.WriteLine(term);
    }
}

Output

1
1
2
3
5
8
13
21
34
55

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents