The C# Foreach loop is useful to iterate through each item in a collection. Generally, this foreach loop is helpful with ArrayList, Generics, etc. The syntax of the C# foreach loop is
foreach(<datatype> <variable> in <list>)
{
statements;
}
Here, the <datatype> is nothing but the type of the item present in the list. For example, the type of the list is int[], then the <datatype> will be integer or int.
The variable can be anyone, but we suggest a meaningful one.
in is a mandatory keyword.
The list is an array or even a collection.
Here, the foreach syntax variable is a read-only variable that will read a value from the list as long the list returns the value. Let us see an example code using the foreach loop.
C# Foreach loop example
We are writing C# code by defining one integer array holding four values in it. Using the foreach loop, we will print all the items in the integer array list.
using System;
class program
{
public static void Main()
{
int[] array= { 1, 2, 3, 4 };
Console.WriteLine("Items in the array are");
foreach (int i in array)
{
Console.Write("{0} ", i);
}
Console.ReadLine();
}
}
OUTPUT
In this C# foreach loop example, the array is an integer array holding four values 1, 2, 3, 4. As shown in the syntax, we just have taken a variable i of type integer to read values or items from the list array[].
i reads one item from the list at a time, and the foreach loop repeats until the last item in the list returned.
Here we are printing all values which the variable i is reading from the list array[].