C# Foreach Loop

The foreach loop in C# is used to iterate over elements of a collection or array. It simplifies iteration by handling the enumerator internally, making the code more readable and less error-prone compared to manual index manipulation.

Key Topics

1. Syntax of Foreach Loop

foreach (type variableName in collection)
{
    // Code to execute for each element
}

The loop iterates over each element in the collection, assigning it to variableName in each iteration.

2. Basic Foreach Loop Example

Example: Iterating Over an Array

string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Output:

Apple
Banana
Cherry

Code Explanation: The loop iterates over the fruits array, printing each fruit name. There's no need to manage an index variable.

3. Foreach Loop with List

Example: Iterating Over a List

using System.Collections.Generic;

List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

Code Explanation: The foreach loop iterates over each integer in the numbers list, printing its value.

4. Limitations of Foreach Loop

The foreach loop is read-only with respect to the collection. You cannot modify the collection (e.g., add or remove elements) while iterating.

Example: Attempting to Modify Collection

foreach (int num in numbers)
{
    if (num == 30)
    {
        numbers.Remove(num);  // Throws InvalidOperationException
    }
}

Explanation: Modifying the collection during iteration causes a runtime exception. To modify a collection, use a for loop or collect items to remove after the loop.

5. Best Practices for Foreach Loops

  • Use foreach when you need to iterate over all elements without modifying the collection.
  • Avoid modifying the collection inside a foreach loop to prevent exceptions.
  • Prefer foreach over for loops when index access is not required.
  • Be mindful of the type of elements when declaring the loop variable.

Key Takeaways

  • The foreach loop simplifies iteration over collections and arrays.
  • It provides a cleaner syntax and reduces the chance of errors related to index management.
  • Collections should not be modified during iteration in a foreach loop.
  • Use foreach when you need to access each element sequentially.
  • Understanding the limitations of foreach helps in choosing the appropriate loop construct.