Coding/Learn/csharp/foreach loop
C# Foundational Course
01.Why C# & .NET Power Modern Software
02.Anatomy of a C# Application
03.Variables & The C# Type System
04.Console I/O: Reading & Writing
05.String Interpolation & Modern Formatting
06.Arithmetic, Math Class & Modulo
07.Conditional Branching: if, else if, and else
08.Logical Operators (&&, ||, !)
09.Switch Statements & Modern Switch Expressions
10.While & Do-While Loops
11.The Standard For Loop & Counting
12.Loop Control: break and continue
13.Methods: Modular, Reusable Code Blocks
14.Optional Parameters, Named Arguments & out/ref
15.Fixed-Size Arrays & Zero-Based Indexing
16.The Sacred Foreach Loop
17.Dynamic Collections: List<T> & Generics
18.Classes & Objects: The OOP Blueprint
19.Auto-Properties & Constructors
20.Capstone: RPG Character & Inventory Engine
Course Certificate0%

Complete all lessons to earn

LearnThe Sacred Foreach Loop
16 / 20 0%
Lesson 16 of 20
5 mins read

The Sacred Foreach Loop

PreviousNext Lesson
In Plain English

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.

The Mental Model

"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.

PointCore Rules to Remember

Point star
Zero Off-By-One Bugs: Impossible to go out of bounds or crash on index math.
Point star
Works on All Collections: Universal syntax for arrays, lists, sets, and database query streams.
Point star
Read-Only Safety: Prevents accidental element reassignment during traversal.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Use foreach whenever you only need to read elements and don't need their index numbers!

Live Interactive Example

Hit Run Code to see it live
Foreach Loop Showcase
C# 12 / .NET
1
2
3
4
5
6
7
8
9
10
11
12
Output Console
Click "Run Code" to view the rendered output.
How it works: The foreach loop cleanly processes every string in the array.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Sum numbers with foreach

  • PointDeclare int[] prices = { 10, 20, 30 };
  • PointSum all prices using a foreach loop and print "Total: $60".
1
2
3
4
5
6
7
8
9
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates