`yield return` defines an iterator. The compiler generates a state machine that produces one value each time the consumer advances the enumerator. This enables lazy streaming without building the entire result collection. `yield break` ends iteration.
```csharp
public static IEnumerable<int> Fibonacci(int count)
{
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
int current = 0;
int next = 1;
for (int index = 0; index < count; index++)
{
yield return current;
(current, next) = (next, checked(current + next));
}
}
foreach (int value in Fibonacci(7))
Console.WriteLine(value); // 0, 1, 1, 2, 3, 5, 8
```
The method body starts when enumeration begins, not when `Fibonacci` is called. Each enumeration runs it again. Resource cleanup in a `using` or `finally` still occurs when the enumerator is disposed, so consumers should dispose enumerators—`foreach` does this automatically. For asynchronous streams, use `async IAsyncEnumerable<T>` with `yield return` and consume using `await foreach`.
Prince Yadav · · 0 likes
yield turns a method into an iterator: it produces a sequence one item at a time, on demand, without building the whole collection in memory first.
Basic example
public static IEnumerable<int> EvenNumbers(int max)
{
for (int i = 0; i <= max; i += 2)
yield return i; // hands back one value and pauses here
}
foreach (var n in EvenNumbers(10))
Console.Write(n + " "); // 0 2 4 6 8 10
How it works
- The compiler generates a state machine class implementing IEnumerable<T> and IEnumerator<T>.
- Each call to MoveNext() runs the method until the next yield return, returns that value, and remembers where it stopped.
- yield break ends the sequence early.
- Execution is deferred: nothing in the method runs until enumeration begins.
Benefits
- Memory efficiency: stream large data (reading a huge file line by line, paging through API results) without loading everything.
public static IEnumerable<string> ReadErrorLines(string path)
{
foreach (var line in File.ReadLines(path))
if (line.Contains("ERROR")) yield return line;
}
- Lazy evaluation: callers can stop early, for example with First() or Take(5), and remaining items are never produced.
- Infinite sequences: generate values forever (Fibonacci, IDs) and let the caller decide how many to take.
- Clean code: no need to manage a temporary list.
Async streams (C# 8+)
Combine yield with await using IAsyncEnumerable<T>:
public async IAsyncEnumerable<Order> GetOrdersAsync([EnumeratorCancellation] CancellationToken ct = default)
{
string? cursor = null;
do
{
var page = await _api.GetPageAsync(cursor, ct);
foreach (var order in page.Items) yield return order;
cursor = page.NextCursor;
} while (cursor != null);
}
await foreach (var order in GetOrdersAsync(ct)) { ... }
Things to be careful about
- Deferred execution means argument validation inside an iterator runs only when enumeration starts; put validation in a non-iterator wrapper method if you need immediate errors.
- Enumerating twice runs the method twice (re-reading files, repeating API calls); call ToList() if you need multiple passes.
- yield cannot be used inside try blocks that have catch clauses (it can be used in try/finally), and iterators cannot have ref or out parameters.