IEnumerable, yield and Custom Iterators
What Does foreach Really Do?
foreach works on anything that implements IEnumerable<T>. That interface hands out an enumerator, which moves item by item. Arrays, lists, dictionaries and LINQ results all do this.
Creating a Sequence with yield return
csharp
IEnumerable<int> CountTo(int max)
{
for (int i = 1; i <= max; i++)
{
Console.WriteLine($"producing {i}");
yield return i; // hand one item out and pause here
}
}
foreach (int n in CountTo(3))
{
Console.WriteLine($"got {n}");
}
Result
The output alternates: producing 1, got 1, producing 2, got 2, ... Items are made one at a time, only when the loop asks for them.
Why This Is Useful
- Lazy: nothing is computed until needed
- Memory friendly: you never hold the whole list
- Works with huge or infinite sequences
csharp
IEnumerable<long> Fibonacci()
{
long a = 0, b = 1;
while (true) // infinite sequence
{
yield return a;
(a, b) = (b, a + b);
}
}
var first10 = Fibonacci().Take(10).ToList(); // only 10 are ever computed
yield break
csharp
IEnumerable<string> ReadUntilStop(IEnumerable<string> lines)
{
foreach (var line in lines)
{
if (line == "STOP") yield break; // end the sequence early
yield return line;
}
}
Reading a Big File Lazily
csharp
IEnumerable<string> ErrorLines(string path) =>
File.ReadLines(path).Where(line => line.Contains("ERROR"));
foreach (var line in ErrorLines("app.log"))
Console.WriteLine(line); // the whole file is never loaded at once
Async Streams
csharp
async IAsyncEnumerable<int> GenerateAsync()
{
for (int i = 1; i <= 3; i++)
{
await Task.Delay(500); // simulate waiting for data
yield return i;
}
}
await foreach (int n in GenerateAsync())
Console.WriteLine(n);
Beware of enumerating twice: A lazy sequence runs its code again each time you loop over it. If the work is expensive, call
ToList() once and reuse the result.
Conclusion
yield return builds lazy sequences easily, and IEnumerable<T> is the common language of collections and LINQ.
Quick Summary: yield return = produce items one at a time, on demand.

