Python The Sacred Foreach Loop
When you need to read every element in an array or collection from start to finish, the foreach loop is the gold standard in C#. It eliminates manual index variables (i = 0; i < len; i++), preventing off-by-one errors completely.
"A standard for loop is like flipping through a book by looking at page numbers (Page 1, Page 2, Page 3). A foreach loop is like a conveyor belt that hands you each physical page directly one after another."
Deep Dive: How It Works
Syntax: foreach (var item in collection) { ... }
Read-Only Iteration: The iteration variable in a foreach loop is read-only (you cannot reassign item = 5; inside the loop).
IEnumerable Interface: foreach works on any C# data structure that implements IEnumerable (Arrays, Lists, Dictionaries, HashSets).
Syntax Blueprint
string[] heroes = { "Batman", "Superman" };
foreach (string hero in heroes) {
Console.WriteLine(hero);
}Iterates through every element cleanly without index variables.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Trying to modify the collection during a foreach loop: list.Remove(item);Why it happens: Invalidates the underlying collection enumerator.
How to fix: Use a standard for loop or LINQ filtering when modifying collections during iteration.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Sum numbers with foreach
Declare int[] prices = { 10, 20, 30 };
Sum all prices using a foreach loop and print "Total: $60".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.