TExcelTAD
Home › C# › C# Foreach Loop

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

csharp
foreach (type item in collection)
{
    // use item
}
csharp · try it yourself
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:

csharp · try it yourself
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.

csharp · try it yourself
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 List while iterating it with foreach — the next step throws an InvalidOperationException.
  • There is no built-in index. If you need one, use a for loop or keep a counter.
csharp · try it yourself
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?

  1. The whole string once
  2. Each character: a, b, c
  3. The indexes 0, 1, 2
  4. It does not compile

What happens if you remove items from a List<T> while looping over it with foreach?

  1. The removed items are skipped
  2. An InvalidOperationException is thrown
  3. The loop restarts
  4. Nothing special