foreach Loop (C#)

A foreach loop walks through every item in a collection such as an array or List<T>, giving you each element one at a time. It is the simplest way to iterate in C#.

C#

You don't manage an index with foreach — it handles that for you, which makes the code cleaner and avoids off-by-one mistakes. The loop variable is read-only.

Use foreach when you just need each item; switch to a for loop when you need the index or want to modify the collection while looping.

Syntax

foreach (var item in collection) { ... }

Examples

C#

string[] fruits = { "apple", "pear" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Output:

apple
pear

Learn it in a lesson

See also

Back to the Dictionary