The foreach loop
Learn to iterate over collections with foreach.
The foreach loop
To walk through all elements of a collection in order you use foreach. The form foreach (var item in items) { ... } takes each element one by one; no counter or index is needed.
Array, list or any other collection does not matter; foreach uses the same pattern for all. It is read-only; you cannot modify the collection while iterating. So when you need to change it during the loop, prefer for.
foreach and readonly
In a foreach loop the loop variable is read-only; you cannot assign to it. A line like item = 5; raises a compile error. To modify elements, use for with an index.
This restriction is by design: foreach is meant to walk a collection safely and fast. When changes are needed, the pattern for (int i = 0; i < items.Length; i++) { items[i] = ...; } is the right approach.
Exercise Print names with foreach
Declare a names array: { "Alex", "Sam", "Kim" }. Use foreach to print each name with Console.WriteLine.
Show example solution
Write string[] names = { "Alex", "Sam", "Kim" }; foreach (var name in names) { Console.WriteLine(name); }
Example solution:
using System;
class Program
{
static void Main()
{
string[] names = { "Alex", "Sam", "Kim" };
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Test yourself
-
What does foreach (var x in arr) Console.WriteLine(x); do?
int[] arr = {1, 2, 3}; foreach (var x in arr) Console.WriteLine(x);- Prints each element of arr in order
- Prints only the first element
- Prints arr sorted
- Does nothing
Show answer
Prints each element of arr in order — Correct. foreach takes each element of the collection in order.
-
Match each foreach part to its meaning
- foreach
- Loop start
- var item
- Loop variable
- in
- Collection connector
- items
- Collection name
-
Write the foreach header
int[] nums = {10, 20, 30}; ____ (var n in nums) { Console.WriteLine(n); }Show answer
int[] nums = {10, 20, 30}; foreach (var n in nums) { Console.WriteLine(n); }