C# foreach loop


The foreach loop in C# is used to iterate over a collection, such as an array, list, or any other collection that implements the IEnumerable interface. It simplifies the process of iterating through items without needing to manage an index or loop counter explicitly.

Syntax of foreach Loop:

foreach (dataType item in collection) { // Code to execute for each item in the collection }

Explanation:

  • dataType: The type of each item in the collection (e.g., int, string).
  • item: A variable representing the current element in the collection.
  • collection: The collection (like an array or list) that you want to iterate over.

Unlike a for loop, the foreach loop automatically moves through the collection from the first to the last element, and no index is required.

Example of a foreach Loop:

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

Explanation:

  • string[] fruits: An array of strings containing fruit names.
  • fruit: A variable that represents the current fruit in the array during each iteration.
  • The loop iterates over each element in the fruits array and prints it.

Output:

Apple Banana Cherry Mango

In this example, the foreach loop iterates over each element in the fruits array and prints its value.


How foreach Works:

  1. Initialization: The loop starts with the first element in the collection.
  2. Iteration: The loop continues to iterate over each element in the collection, automatically moving to the next element after processing the current one.
  3. Termination: The loop terminates when it has iterated over all the elements in the collection.

Another Example with a List:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; foreach (int number in numbers) { Console.WriteLine("Number: " + number); }

Explanation:

  • List<int>: A list of integers containing numbers from 1 to 5.
  • The foreach loop iterates over the list and prints each number.

Output:

Number: 1 Number: 2 Number: 3 Number: 4 Number: 5

In this example, the foreach loop iterates through the numbers list and prints each element.


foreach with a Dictionary:

You can also use foreach to iterate over key-value pairs in a dictionary.

Dictionary<string, int> ages = new Dictionary<string, int>() { { "Alice", 30 }, { "Bob", 25 }, { "Charlie", 35 } }; foreach (KeyValuePair<string, int> entry in ages) { Console.WriteLine(entry.Key + " is " + entry.Value + " years old."); }

Explanation:

  • Dictionary<string, int>: A dictionary where the key is a string (name), and the value is an integer (age).
  • The foreach loop iterates over the dictionary and processes each key-value pair.

Output:

Alice is 30 years old. Bob is 25 years old. Charlie is 35 years old.

foreach and Multidimensional Arrays:

You can also use a foreach loop to iterate over multidimensional arrays, but the iteration will go through each element in the array without knowing the row/column explicitly.

int[,] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; foreach (int number in matrix) { Console.WriteLine(number); }

Explanation:

  • int[,] matrix: A 2D array with 3 rows and 2 columns.
  • The foreach loop iterates over all the elements in the array.

Output:

1 2 3 4 5 6

The foreach loop iterates through each element in the 2D array in row-major order (left to right, top to bottom).


Important Notes about foreach:

  1. Read-Only: The foreach loop does not allow modification of the collection items directly. If you need to modify elements, consider using a for loop or modify the collection outside the loop.

    Example of trying to modify:

    foreach (string fruit in fruits) { fruit = "Orange"; // Error: Cannot modify collection elements }
  2. Safe Iteration: The foreach loop ensures you don’t go out of bounds (as might happen with an index in a for loop). It iterates safely through all elements in the collection.

  3. Performance Considerations: While convenient, the foreach loop might have slightly less performance efficiency than a for loop when you require indexing (though the difference is typically negligible).


Summary:

  • The foreach loop in C# is used to iterate over collections (like arrays, lists, dictionaries) easily without managing an index.
  • It simplifies iteration and makes your code cleaner.
  • It does not allow modifying the items of the collection directly within the loop.