ZetCode

C# yield

last modified November 6, 2026

In this article we show how to use the yield keyword in C# language.

The yield keyword

The yield keyword is used to do custom stateful iteration over a collection. The yield keyword tells the compiler that the method in which it appears is an iterator block.

yield return <expression>;
yield break;

The yield return statement returns one element at a time. The return type of an iterator is IEnumerable<T>, IEnumerator<T>, their non-generic versions, or IAsyncEnumerable<T> for asynchronous iterators. The yield break statement ends the iteration.

We consume an iterator with a foreach loop or with LINQ. Each iteration of the loop asks the iterator for the next element. When a yield return statement is reached, the expression is returned, and the current location in code is retained. Execution resumes from that location the next time the next element is requested.

Two important aspects of using yield are:

C# Fibonacci without yield

In the first examples, we work with the Fibonacci sequence.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The Fibonacci sequence is the series of numbers, where the next number is found by adding up the two numbers before it.

Program.cs
var data = Fibonacci(10);

foreach (int e in data)
{
    Console.Write($"{e} ");
}

Console.WriteLine();

IEnumerable<int> Fibonacci(int n)
{
    var vals = new List<int>();

    for (int i = 0, n1 = 0, n2 = 1; i < n; i++)
    {
        vals.Add(n1);

        int temp = n1 + n2;
        n1 = n2;
        n2 = temp;
    }

    return vals;
}

Here, we compute the sequence without the yield keyword. We print the first ten values of the sequence.

var vals = new List<int>();

This implementation requires a new list. If we worked with hundreds of millions of values, the list would require a huge amount of memory, and the caller could not start processing until all values were computed.

$ dotnet run
0 1 1 2 3 5 8 13 21 34 

C# Fibonacci with yield

Next, we use the yield keyword to generate the Fibonacci sequence.

Program.cs
foreach (int fib in Fibonacci(10))
{
    Console.Write($"{fib} ");
}

Console.WriteLine();

IEnumerable<int> Fibonacci(int n)
{
    for (int i = 0, n1 = 0, n2 = 1; i < n; i++)
    {
        yield return n1;

        int temp = n1 + n2;
        n1 = n2;
        n2 = temp;
    }
}

This implementation produces numbers one by one, as the consumer requests them.

for (int i = 0, n1 = 0, n2 = 1; i < n; i++)
{
    yield return n1;

    int temp = n1 + n2;
    n1 = n2;
    n2 = temp;
}

The yield return statement returns the current value to the foreach statement. The values of i, n1, and n2 are remembered between calls; the compiler generates a state machine class behind the scenes to keep them.

$ dotnet run
0 1 1 2 3 5 8 13 21 34 

C# yield lazy evaluation

The following example shows how the control passes between the iterator and its consumer.

Program.cs
foreach (var e in Numbers())
{
    Console.WriteLine($"consumer got {e}");
}

IEnumerable<int> Numbers()
{
    Console.WriteLine("iterator started");

    for (int i = 1; i <= 3; i++)
    {
        Console.WriteLine($"producing {i}");
        yield return i;
    }

    Console.WriteLine("iterator finished");
}

Both the iterator and the loop print messages.

Console.WriteLine($"producing {i}");
yield return i;

The output shows that each value is consumed right after it is produced. The iterator is paused at the yield return statement while the loop body runs.

$ dotnet run
iterator started
producing 1
consumer got 1
producing 2
consumer got 2
producing 3
consumer got 3
iterator finished

C# yield infinite sequence

Since values are produced on demand, an iterator can describe an infinite sequence. The consumer decides how many values it needs.

Program.cs
var first = FibSeq().Take(12);
Console.WriteLine(string.Join(" ", first));

var below1000 = FibSeq().TakeWhile(f => f < 1000);
Console.WriteLine(string.Join(" ", below1000));

var evens = FibSeq().Where(f => f % 2 == 0).Skip(1).Take(5);
Console.WriteLine(string.Join(" ", evens));

IEnumerable<long> FibSeq()
{
    long a = 0, b = 1;

    while (true)
    {
        yield return a;
        (a, b) = (b, a + b);
    }
}

The FibSeq iterator never ends on its own.

while (true)
{
    yield return a;
    (a, b) = (b, a + b);
}

The loop runs forever, but it is paused after each value. The tuple assignment computes the next pair of numbers.

var first = FibSeq().Take(12);

The Take method stops the enumeration after twelve values.

var below1000 = FibSeq().TakeWhile(f => f < 1000);

The TakeWhile method stops at the first value which does not satisfy the condition.

var evens = FibSeq().Where(f => f % 2 == 0).Skip(1).Take(5);

LINQ methods can be combined freely; we get five even Fibonacci numbers, skipping zero.

$ dotnet run
0 1 1 2 3 5 8 13 21 34 55 89
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
2 8 34 144 610

C# multiple yield statements and yield break

An iterator can have multiple yield return statements. The yield break statement ends the sequence early.

Program.cs
foreach (var day in WorkDays())
{
    Console.Write($"{day} ");
}

Console.WriteLine();

foreach (var word in WordsUntil(["sky", "war", "stop", "cloud", "owl"], "stop"))
{
    Console.Write($"{word} ");
}

Console.WriteLine();

IEnumerable<string> WorkDays()
{
    yield return "Monday";
    yield return "Tuesday";
    yield return "Wednesday";
    yield return "Thursday";
    yield return "Friday";
}

IEnumerable<string> WordsUntil(IEnumerable<string> words, string sentinel)
{
    foreach (var word in words)
    {
        if (word == sentinel)
        {
            yield break;
        }

        yield return word;
    }
}

We have two iterators.

yield return "Monday";
yield return "Tuesday";

The WorkDays iterator returns five values from five yield return statements, one after another.

if (word == sentinel)
{
    yield break;
}

The WordsUntil iterator stops when it reaches the sentinel word. The remaining words are never returned.

$ dotnet run
Monday Tuesday Wednesday Thursday Friday 
sky war 

C# yield running total

An iterator keeps its local state between the produced values; the next program demonstrates this.

Program.cs
List<int> vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

foreach (int e in RunningTotal(vals))
{
    Console.Write($"{e} ");
}

Console.WriteLine();

IEnumerable<int> RunningTotal(IEnumerable<int> data)
{
    int runningTotal = 0;

    foreach (int val in data)
    {
        runningTotal += val;
        yield return runningTotal;
    }
}

The example calculates the running total for a list of integers.

runningTotal += val;
yield return runningTotal;

The runningTotal variable keeps its value while the control goes back and forth between the iterator and its consumer.

$ dotnet run
1 3 6 10 15 21 28 36 45 55 

C# yield and argument validation

Because of deferred execution, the code before the first yield return does not run when the iterator method is called. This includes argument checks.

Program.cs
var res = Repeat("ab", -1);
Console.WriteLine("iterator created");

try
{
    foreach (var e in res)
    {
        Console.WriteLine(e);
    }
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine($"late error: {e.ParamName}");
}

try
{
    var res2 = RepeatChecked("ab", -1);
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine($"early error: {e.ParamName}");
}

Console.WriteLine(string.Join(" ", RepeatChecked("ab", 3)));

IEnumerable<string> Repeat(string s, int count)
{
    ArgumentOutOfRangeException.ThrowIfNegative(count);

    for (int i = 0; i < count; i++)
    {
        yield return s;
    }
}

IEnumerable<string> RepeatChecked(string s, int count)
{
    ArgumentOutOfRangeException.ThrowIfNegative(count);

    return Iterate();

    IEnumerable<string> Iterate()
    {
        for (int i = 0; i < count; i++)
        {
            yield return s;
        }
    }
}

We call two versions of a method with an invalid argument.

var res = Repeat("ab", -1);
Console.WriteLine("iterator created");

The Repeat call succeeds even though the count is negative. The exception is thrown only later, when the foreach loop starts the enumeration, possibly far from the bug.

ArgumentOutOfRangeException.ThrowIfNegative(count);

return Iterate();

The RepeatChecked method is not an iterator itself; it validates the argument eagerly and then returns a local iterator function. The error is reported at the call site.

$ dotnet run
iterator created
late error: count
early error: count
ab ab ab

C# yield and finally

An iterator may contain a try/finally block. The finally block runs even when the consumer stops the enumeration early, because foreach disposes the enumerator.

Program.cs
foreach (var line in ReadLines())
{
    Console.WriteLine(line);

    if (line == "line 2")
    {
        break;
    }
}

IEnumerable<string> ReadLines()
{
    Console.WriteLine("opening resource");

    try
    {
        for (int i = 1; i <= 5; i++)
        {
            yield return $"line {i}";
        }
    }
    finally
    {
        Console.WriteLine("closing resource");
    }
}

We simulate reading lines from a resource.

if (line == "line 2")
{
    break;
}

The loop ends after the second line. The finally block of the iterator still runs, so the resource is closed.

$ dotnet run
opening resource
line 1
line 2
closing resource

C# async iterator

Since C# 8, iterators can be asynchronous. An async iterator returns IAsyncEnumerable<T> and may use await between the yield return statements. It is consumed with await foreach.

Program.cs
await foreach (var reading in ReadSensor(4))
{
    Console.WriteLine($"{reading.Time:HH\\:mm\\:ss\\.f} - sample {reading.Id}");
}

async IAsyncEnumerable<(int Id, TimeOnly Time)> ReadSensor(int count)
{
    for (int i = 1; i <= count; i++)
    {
        await Task.Delay(300);
        yield return (i, TimeOnly.FromDateTime(DateTime.Now));
    }
}

We simulate a sensor that produces a sample every 300 milliseconds.

await Task.Delay(300);
yield return (i, TimeOnly.FromDateTime(DateTime.Now));

The iterator waits asynchronously without blocking a thread and then returns the sample with a timestamp.

await foreach (var reading in ReadSensor(4))

The await foreach statement awaits each element as it becomes available.

$ dotnet run
18:53:44.4 - sample 1
18:53:44.7 - sample 2
18:53:45.0 - sample 3
18:53:45.3 - sample 4

C# yield partition example

In the next example, we compare the memory consumption of two approaches to partitioning a huge sequence.

Program.cs
var vals = Enumerable.Range(1, 100_000_000);

var option = int.Parse(args[0]);

IEnumerable<int[]> result = option == 1 ? Partition1(vals, 5) : Partition2(vals, 5);

int parts = 0;
int[]? first = null;
int[]? last = null;

foreach (var part in result)
{
    first ??= part;
    last = part;
    parts++;
}

Console.WriteLine($"parts: {parts}");
Console.WriteLine(string.Join(", ", first!));
Console.WriteLine(string.Join(", ", last!));

IEnumerable<int[]> Partition1(IEnumerable<int> source, int size)
{
    var data = new List<int[]>();
    var chunk = new List<int>(size);

    foreach (int item in source)
    {
        chunk.Add(item);

        if (chunk.Count == size)
        {
            data.Add([.. chunk]);
            chunk.Clear();
        }
    }

    if (chunk.Count > 0)
    {
        data.Add([.. chunk]);
    }

    return data;
}

IEnumerable<int[]> Partition2(IEnumerable<int> source, int size)
{
    var chunk = new List<int>(size);

    foreach (int item in source)
    {
        chunk.Add(item);

        if (chunk.Count == size)
        {
            yield return [.. chunk];
            chunk.Clear();
        }
    }

    if (chunk.Count > 0)
    {
        yield return [.. chunk];
    }
}

We have a sequence of a hundred million values. We partition them into groups of five values with and without the yield keyword and compare the efficiency.

var vals = Enumerable.Range(1, 100_000_000);

A sequence of one hundred million values is generated with Enumerable.Range. It is lazy; the numbers are not stored in memory.

IEnumerable<int[]> result = option == 1 ? Partition1(vals, 5) : Partition2(vals, 5);

The program is run with a parameter. The option 1 invokes the Partition1 function; any other option invokes the Partition2 iterator.

foreach (var part in result)
{
    first ??= part;
    last = part;
    parts++;
}

We enumerate the result once; we count the parts and remember the first and the last one.

var data = new List<int[]>();

The Partition1 function builds a list holding all twenty million partitions before it returns.

yield return [.. chunk];

In Partition2, we return one partition at a time. Each partition can be garbage-collected as soon as the consumer is done with it. For real code, the built-in LINQ Chunk method does the same job.

We build the program as a console project in Release mode and use the time command to compare the two functions. The %M format gives the peak memory usage.

$ /usr/bin/time -f "%M KB %e s" bin/Release/net10.0/Partition 1
parts: 20000000
1, 2, 3, 4, 5
99999996, 99999997, 99999998, 99999999, 100000000
1371040 KB 1.96 s

$ /usr/bin/time -f "%M KB %e s" bin/Release/net10.0/Partition 2
parts: 20000000
1, 2, 3, 4, 5
99999996, 99999997, 99999998, 99999999, 100000000
39308 KB 0.68 s

Source

yield statement - language reference

In this article we have worked with C# yield keyword.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.