When we have a list of elements (like an array) or basically an iterable object and want to run a block of code for each element of that list, we can use the foreach loop.
Here’s the structure of the foreach loop:
foreach (type variableName in iterableList) {
// code block to be executed
}
for: to create a foreach loop, we start with the keyword foreach.
(): inside the parentheses that comes after the keyword foreach we set the name of the list (that contains the elements) and a variable of the same type that will receive each value of the list and this variable and its value can be used in the body of the foreach loop.
` iterableList `: this is the list that contains the elements.
varaibleName: This is the variable that each element of the list will be stored in it.
in: we use the keyword in to separate iterableList from variableName.
`{}`: the pair of braces that comes after the parentheses, declares the scope (body) of the loop.
Example:
using System;
namespace quickExample
{
public class Program
{
public static void Main(string[] args)
{
int [] iArray = { 1, 2, 3, 4, 5, 56, 6, 7, 23, 423, 42, 34, 23, 423, 42, 3 };
foreach (int i in iArray)
{
Console.Write(i + ", ");
}
}
}
}
Output: 1,2,3,4,5,56,6,7,23,423,42,34,23,423,42,3
Here we used an array variable that is named iArray. In the array section you’ll learn more about this type of variables but in short, it’s a type of variable that allows developers to store multiple values instead of only one.
So here via the foreach loop, we looped through the elements of this list and sent its values to the output stream (console in this case).