The foreach loop in C# is a specialized control flow statement that is used to iterate over each element of a collection, such as arrays, lists, or other enumerable types. the foreach loop automatically handles the iteration of the collection, simplifying the code needed to access each element.
It is particularly useful when the exact number of iterations is not known or when the goal is to access each element in the collection.
Characteristics of the foreach Loop
1. Automatic Iteration: The foreach loop automatically iterates over the elements of a collection without needing to manage an index or counter variable.
2. Read-Only Access: The loop provides read-only access to the elements of the collection. While you can access each element, you cannot modify the collection itself during iteration.
3. Simplified Syntax: The syntax of the foreach loop is concise, eliminating the need to manually track the collection’s length or handle the loop termination condition.
Syntax:
foreach (type element in collection)
{
// Code to execute for each element
}
Explanation of Syntax:
- type: The type of the elements in the collection (e.g., int, string, char).
- element: A variable representing the current element in the collection, which takes the value of each element in the collection during each iteration.
- collection: The enumerable collection (such as an array, list, or any object that implements IEnumerable).
Example:
using System;
class ProgramExample
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number); // Prints each number in the array
}
}
}
Output:
2
3
4
5
Example 2: Print the name
using System;
class ProgramExample
{
static void Main()
{
string[] names = { "John", "Tom", "Mark" };
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Tom
Mark