yield return lets a method produce a sequence one item at a time, without building a list first. The compiler turns the method into an iterator: a small state machine that runs your code up to the next yield return, hands back that value, and pauses until the caller asks for the next one. yield break ends the sequence early.
A method that uses yield must return IEnumerable<T>, IEnumerator<T> (or their non-generic versions), or IAsyncEnumerable<T> for async iterators.
A first example
foreach (int value in Powers(2, 10))
{
Console.Write($"{value} ");
}
// 2 4 8 16 32 64 128 256 512 1024
static IEnumerable<int> Powers(int number, int exponent)
{
int result = 1;
for (int i = 0; i < exponent; i++)
{
result *= number;
yield return result;
}
}
The same method without yield would create a List<int>, fill it with all ten values and return it. With yield, each value is computed only when the foreach loop asks for it, and nothing is stored.
Lazy sequences, even infinite ones
Because values are produced on demand, a sequence does not have to end. The caller decides how much to take:
foreach (long n in Fibonacci().Take(10))
{
Console.Write($"{n} ");
}
// 0 1 1 2 3 5 8 13 21 34
static IEnumerable<long> Fibonacci()
{
long a = 0, b = 1;
while (true)
{
yield return a;
(a, b) = (b, a + b);
}
}
The while (true) loop is safe here because Take(10) stops asking after ten items. Calling Fibonacci().ToList() would never finish: the list keeps growing until the process runs out of memory, and after the 92nd Fibonacci number the values silently overflow long.
Ending early with yield break
yield break stops the sequence, like return in a normal method:
static IEnumerable<string> LinesUntilBlank(IEnumerable<string> lines)
{
foreach (string line in lines)
{
if (string.IsNullOrWhiteSpace(line))
yield break;
yield return line;
}
}
Traps
Nothing runs until you enumerate. Calling an iterator method only creates the iterator object. Not even the first line of its body executes. That surprises people when the method validates its arguments:
static IEnumerable<string> ReadLines(string path)
{
ArgumentNullException.ThrowIfNull(path); // does not run on the call
foreach (string line in File.ReadLines(path))
yield return line;
}
var lines = ReadLines(null!); // no exception here
foreach (var line in lines) { } // ArgumentNullException is thrown here
The fix is to split the method in two: a normal method that validates and then returns the result of a private iterator, often written as a local function.
static IEnumerable<string> ReadLines(string path)
{
ArgumentNullException.ThrowIfNull(path); // runs immediately
return Iterator();
IEnumerable<string> Iterator()
{
foreach (string line in File.ReadLines(path))
yield return line;
}
}
Every enumeration runs the method again. Looping over the same iterator twice executes its body twice. If the body reads a file or queries a database, you pay twice, and the results may differ. Call ToList() once if you need the values more than once.
try, catch and finally. A yield return cannot appear inside a try block that has a catch clause, or inside a catch or finally block. It is allowed in a try with only a finally, and using statements work too. The finally block runs when the loop finishes or when the caller stops early with break, because foreach disposes the enumerator. That is what makes it safe to open a file inside an iterator.
No ref or out parameters. Iterator methods cannot have them.
Async iterators
Since C# 8, an async method can return IAsyncEnumerable<T> and use both await and yield return. The caller consumes it with await foreach:
await foreach (int i in CountSlowlyAsync(3))
{
Console.WriteLine(i);
}
static async IAsyncEnumerable<int> CountSlowlyAsync(int count)
{
for (int i = 1; i <= count; i++)
{
await Task.Delay(500);
yield return i;
}
}
This is the natural shape for paging through an API or streaming rows from a database: each item is processed as soon as it arrives, without waiting for the whole result. ASP.NET Core can also stream an IAsyncEnumerable<T> returned from an endpoint as a JSON array.