C# Foreach Loop
The foreach loop visits every element of a collection — an array, a list, the characters of a string, the entries of a dictionary — without any index bookkeeping. When you just need "each item, one at a time", it is the simplest and safest loop.
Syntax
foreach (type item in collection)
{
// use item
}using System;
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(quot;I like {fruit}");
}I like apple
I like banana
I like cherry
You can write var instead of the element type: foreach (var fruit in fruits). The compiler infers string.
Computing with foreach
Accumulating a sum, finding a maximum or counting matches are typical foreach jobs:
using System;
int[] temperatures = { 18, 22, 25, 19, 30, 27, 21 };
int total = 0;
int max = int.MinValue;
int warmDays = 0;
foreach (int t in temperatures)
{
total += t;
if (t > max) max = t;
if (t >= 25) warmDays++;
}
double average = (double)total / temperatures.Length;
Console.WriteLine(quot;Average: {average:F1}");
Console.WriteLine(quot;Max: {max}");
Console.WriteLine(quot;Warm days: {warmDays}");Average: 23.1
Max: 30
Warm days: 3
Strings, lists and dictionaries
foreach works with anything that implements IEnumerable — every collection in .NET does. A string yields its characters, and a dictionary yields key/value pairs.
using System;
using System.Collections.Generic;
foreach (char c in "C#!")
Console.Write(quot;[{c}]");
Console.WriteLine();
var stock = new Dictionary<string, int>
{
["pens"] = 40,
["notebooks"] = 12,
["erasers"] = 25
};
foreach (var (item, count) in stock)
Console.WriteLine(quot;{item}: {count}");
var names = new List<string> { "Zoe", "Ali" };
foreach (var name in names)
Console.WriteLine(name.ToUpper());[C][#][!]
pens: 40
notebooks: 12
erasers: 25
ZOE
ALI
var (item, count) deconstructs each KeyValuePair into two variables — shorter than writing pair.Key and pair.Value.
Limitations of foreach
- The loop variable is read-only:
fruit = "kiwi";inside the loop does not compile. - You must not add or remove items from a
Listwhile iterating it withforeach— the next step throws anInvalidOperationException. - There is no built-in index. If you need one, use a
forloop or keep a counter.
using System;
string[] steps = { "Preheat oven", "Mix ingredients", "Bake 25 minutes" };
int number = 1;
foreach (string step in steps)
{
Console.WriteLine(quot;Step {number}: {step}");
number++;
}Step 1: Preheat oven
Step 2: Mix ingredients
Step 3: Bake 25 minutes
for or foreach?
| Situation | Best loop |
|---|---|
| Read every element in order | foreach |
| Need the index, or to modify elements in an array | for |
| Walk backwards or skip elements | for |
| Iterate a dictionary, set or other non-indexed collection | foreach |
Tip: When in doubt, start with
foreach. It cannot go out of bounds and it states your intent clearly.
Test yourself
What does foreach (char c in "abc") iterate over?
- The whole string once
- Each character: a, b, c
- The indexes 0, 1, 2
- It does not compile
What happens if you remove items from a List<T> while looping over it with foreach?
- The removed items are skipped
- An InvalidOperationException is thrown
- The loop restarts
- Nothing special