The foreach
loop in C# executes a block of code on each element in an array or in another collection of items; it is useful for performing the same function on each item.
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 thecollection_variable
.
The code snippet below illustrates the usage of the C# foreach
loop:
class ForEachDemo{static void Main(){// an array of fruit namesstring[] Fruits = {"Apple", "Banana", "Apricot", "Kiwi", "Mango"};// printing the elements of the Fruits array using foreachforeach (string fruit in Fruits){System.Console.WriteLine(fruit);}}}