0Pricing
C# Academy · Lesson

The foreach Loop

Iterate without indices.

What is foreach?

The foreach loop lets you visit every item in a collection one by one.

You don't manage an index or a counter. C# walks the collection for you and hands each element to a variable you name.

It is the cleanest way to read all items in an array or list.

Basic Syntax

The shape is simple: foreach (var item in collection) followed by a body.

On each pass, item holds the next element. The loop ends automatically after the last one.

foreach (var name in names)
{
    Console.WriteLine(name);
}

All lessons in this course

  1. The foreach Loop
  2. Iterating Collections
  3. break and continue
  4. Common Iteration Mistakes
← Back to C# Academy