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
C# foreach loop – Interview Questions
Q 1: What is a foreach loop in C#?
Q 2: Can we modify collection items using foreach?
Q 3: Which data structures support foreach loop?
Q 4: Is foreach loop faster than for loop?
Q 5: Does foreach require an index?
C# foreach loop – Objective Questions (MCQs)
Q1. What is the main purpose of a foreach loop in C#?
Q2. Which of the following data types can be used with a foreach loop?
Q3. Can the control variable in a foreach loop be modified inside the loop?
Q4. What is the correct syntax of a foreach loop?
Q5. What happens if the collection in a foreach loop is empty?