What is the foreach loop in C#?

The foreach loop in C# executes a block of code on each element in an array or in another collection of items; i​t is useful for performing the same function on each item.

svg viewer

Syntax

Have a look at the syntax of the foreach loop in C#:

foreach(data_type var_name in collection_variable)
{
     // statements to be executed
}
  • data_type can be any data type compatible with C#.
  • collection_variable can be any collection of elements (e.g., a list or an array).

The data_type must match the data type of the elements in the collection_variable.

Code

The code snippet below illustrates the usage of the C# foreach loop:

class ForEachDemo
{
static void Main()
{
// an array of fruit names
string[] Fruits = {"Apple", "Banana", "Apricot", "Kiwi", "Mango"};
// printing the elements of the Fruits array using foreach
foreach (string fruit in Fruits)
{
System.Console.WriteLine(fruit);
}
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved