Control Flow: Loops, foreach with IEnumerable & IAsyncEnumerable Streaming
1Concept
foreach iterates over any type implementing IEnumerable or with a GetEnumerator() method. C# 8+ introduced IAsyncEnumerable<T> and await foreach for asynchronous streaming of database rows or Kafka messages without buffering entire collections in memory.
2Architecture Diagram
await foreach (var item in FetchAsyncStream()) ──► Yields items as they arrive over network!
3Code Example
Stage 0 Language Foundations
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
// Asynchronous Streaming Generator
static async IAsyncEnumerable<string> FetchStockUpdatesAsync()
{
string[] stocks = ["AAPL: $185", "MSFT: $420", "NVDA: $120"];
foreach (var s in stocks)
{
await Task.Delay(50); // Simulate network latency
yield return s;
}
}
static async Task Main()
{
Console.WriteLine("=== Consuming IAsyncEnumerable Stream ===");
await foreach (var update in FetchStockUpdatesAsync())
{
Console.WriteLine($"Live Ticker: {update}");
}
}
}4Expected Output
=== Consuming IAsyncEnumerable Stream === Live Ticker: AAPL: $185 Live Ticker: MSFT: $420 Live Ticker: NVDA: $120
5Key Takeaways
- ✓Use IAsyncEnumerable<T> with yield return for real-time streaming APIs.
- ✓foreach over List<T> uses a struct enumerator that allocates zero heap garbage.
- ✓LINQ queries are lazily evaluated until enumerated by foreach or .ToList().