C#•Loops
C# Generic List Collections Iteration Mechanics via Foreach
The foreach loop in C# provides a clean, idiomatic mechanism for iterating through arrays and generic collections like List<T>. Under the hood, the compiler leverages the IEnumerable<T> and IEnumerator<T> interfaces, creating a forward-only read-only iteration cursor that protects collection integrity.
Syntax
List<string> clusterNodes = new List<string> { "Node-A", "Node-B", "Node-C" };
foreach (var node in clusterNodes) {
Console.WriteLine(node);
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| foreach (var item in list) | Construct | Sequential read-only forward enumeration over any IEnumerable<T> collection. |
| List<T> | Collection | Dynamically resizing strongly-typed generic array list. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
using System.Collections.Generic;
public class Program {
public class Microservice {
public string Name { get; set; }
public int Port { get; set; }
public bool IsHealthy { get; set; }
public Microservice(string name, int port, bool isHealthy) {
Name = name;
Port = port;
IsHealthy = isHealthy;
}
}
public static void Main() {
// 1. Initializing Generic List<T>
List<Microservice> meshServices = new List<Microservice> {
new Microservice("auth-service", 8081, true),
new Microservice("billing-api", 8082, true),
new Microservice("reporting-worker", 8083, false),
new Microservice("gateway-ingress", 8080, true)
};
Console.WriteLine("=== Iterating Generic List<T> with Foreach ===");
int onlineCount = 0;
// 2. Foreach iteration pipeline
foreach (var svc in meshServices) {
string statusBadge = svc.IsHealthy ? "[ONLINE]" : "[OFFLINE]";
Console.WriteLine($"{statusBadge} {svc.Name} running on port {svc.Port}");
if (svc.IsHealthy) {
onlineCount++;
}
}
Console.WriteLine($"\nMesh Summary: {onlineCount}/{meshServices.Count} services operating normally.");
}
}Expected Output:
=== Iterating Generic List<T> with Foreach === [ONLINE] auth-service running on port 8081 [ONLINE] billing-api running on port 8082 [OFFLINE] reporting-worker running on port 8083 [ONLINE] gateway-ingress running on port 8080 Mesh Summary: 3/4 services operating normally.
How It Works: Step-by-Step
- Lines 18-23: Constructs a strongly typed generic List<Microservice> containing 4 service objects.
- Lines 29-36: Foreach enumerates through the list, safely reading properties and updating accumulator onlineCount.
- Line 38: Calculates total operational ratio using List<T>.Count.
Key Concepts
- Under the hood, the C# compiler translates foreach into a while loop calling GetEnumerator(), MoveNext(), and Current.
- The iteration variable in a foreach loop is read-only; you cannot reassign the item reference inside the loop body.
- Modifying a List<T> (calling .Add() or .Remove()) during a foreach loop throws an InvalidOperationException to protect collection consistency.
- If you need to remove elements while iterating, iterate backwards with a standard for loop, or use list.RemoveAll(predicate).
Common Mistake: Modifying collection elements inside foreach (InvalidOperationException)
Calling list.Remove(item) or list.Add(item) inside a foreach loop invalidates the enumerator state machine, causing a crash at runtime.
❌ Incorrect
foreach (var s in list) { if (!s.IsHealthy) list.Remove(s); } // Throws InvalidOperationException!✅ Correct
list.RemoveAll(s => !s.IsHealthy); // Safe removal with predicate
Related C# Tutorials & Compiler
C# While and Do-While Loops with Examples
Master pre-test while loops and post-test do-while loops in C#.
C# Break and Continue Statements in Loops
Interrupt or skip loop iterations using break and continue in C#.
C# List<T> and LINQ Queries: Where, Select, and Aggregate
Master dynamic List<T> collections and powerful LINQ queries (Where, Select, Sum).
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.