Foreach loop in C#
Foreach loop in C#
The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. Important points regarding foreach loop – Please enclose the statements of foreach loop in curly brackets. You should declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name instead of declaring and initializing a loop counter variable. You can use the loop variable you created in the loop body.
Syntax:
foreach(datatype variablename in collectionname)
{
// execute the logic
}
Let us see an example –
using System;
class Program
{
static public void Main()
{
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
foreach(int items in arr)
{
Console.WriteLine(items);
}
}
} Output : 1 2 3 4 5 6 7 8 9 0
