Tutorials References Exercises Videos Menu
Create Website Get Certified Upgrade

C# Foreach Loop


The foreach Loop

There is also a foreach loop, which is used exclusively to loop through elements in an array:

Syntax

foreach (type variableName in arrayName) 
{
  // code block to be executed
}

The following example outputs all elements in the cars array, using a foreach loop:

Example

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

Try it Yourself »

Note: Don't worry if you don't understand the example above. You will learn more about Arrays in the C# Arrays chapter.