Back to course

Foreach Loop

C# Zero to Hero: Comprehensive Programming Masterclass

The Foreach Loop

There is a special loop used exclusively to loop through elements in an array or a collection.

Syntax

csharp string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; foreach (string i in cars) { Console.WriteLine(i); }

Why use Foreach?

  • It's more readable.
  • No need for an index counter (i).
  • Less prone to errors (like "Index Out of Range").