The foreach
statement is used to iterate over elements in a collection or an array. It provides a simplified and convenient way to access each element in the collection without the need for explicit indexing. The foreach
loop is commonly used when you want to perform a specific operation on every item in a collection without having to manage the iteration details manually.
Here's the syntax of the foreach
statement:
foreach (var item in collection)
{
// Code block to be executed for each 'item' in the 'collection'.
}
Here's an example of using the foreach
statement to iterate over an array:
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (var number in numbers)
{
Console.WriteLine(number);
}
In this example, the foreach
loop iterates over each element in the numbers
array, and the variable number
takes the value of each element in each iteration. The loop will print the numbers 1, 2, 3, 4, and 5 to the console.
You can also use the foreach
loop with other collections, such as lists, dictionaries, or custom objects that implement the IEnumerable
interface.
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
foreach (var name in names)
{
Console.WriteLine("Hello, " + name + "!");
}
In this example, the foreach
loop iterates over the names
list, and the name
variable takes the value of each element (strings) in each iteration. The loop will print greetings for each name in the list.
Using the foreach
statement is a powerful and concise way to iterate over collections in C#, making the code more readable and reducing the chances of off-by-one errors that can occur with traditional for
loops.