C# foreach Loop (original) (raw)

Last Updated : 03 Feb, 2025

**foreach loop in C# is a special type of loop designed to iterate through collections like arrays, lists, and other enumerable data types. It simplifies the process of accessing each element in a collection without the need for manual indexing. This is useful when performing operations on every element of an array or collection without worrying about the indexes.

**Example 1:

C# `

// C# Program to iterate Through // an Array Using foreach loop using System;

class Geeks { static void Main(string[] args) { char[] arr = { 'G', 'e', 'e', 'k' };

    // Using foreach to print 
    // each character in the array
    foreach(char ch in arr)
    { 
      Console.WriteLine(ch); 
    }
}

}

`

Syntax of foreach Loop

foreach (data_type variable_name in collection)

{
// Code to execute for each element
}

**Parameters:

The foreach loop uses the in keyword to iterate over each item in the specified collection. On each iteration, it selects an item from the collection and stores it in the variable defined. The loop continues until all elements have been processed.

**Important Points:

Flow Diagram of foreach Loop

Foreach-Loop

**Example 2:

C# `

// Counting Elements Based on Conditions using System;

class Geeks { static void Main(string[] args) { char[] gender = { 'm', 'f', 'm', 'm', 'f' }; int maleCount = 0, femaleCount = 0;

    // Counting males and females using foreach
    foreach(char g in gender)
    {
        if (g == 'm')
            maleCount++;
        else if (g == 'f')
            femaleCount++;
    }

    Console.WriteLine("Number of males: " + maleCount);
    Console.WriteLine("Number of females: "
    + femaleCount);
}

}

`

Output

Number of males: 3 Number of females: 2

**Example 3: This example demonstrating the foreach loop in C#, the iteration of different collections (arrays, lists, and dictionaries):

C# `

using System; using System.Collections.Generic;

class Geeks { public static void Main() { // Iterating through an array of strings string[] f = { "Apple", "Banana", "Orange" };

    Console.WriteLine("Fruits:");

    // Iterating through the array and printing each fruit
    foreach (string fruit in f)
    {
        Console.WriteLine(fruit);  
    }
    Console.WriteLine();

    // Iterating through a list of integers
    List<int> n = new List<int> { 10, 20, 30 };

    Console.WriteLine("Numbers:");
    foreach (int number in n)
    {
        Console.WriteLine(number);  
    }
    Console.WriteLine();

    // Iterating through a dictionary
    Dictionary<string, int> ages = new Dictionary<string, int>
    {
        { "A", 30 },
        { "B", 25 },
        { "C", 35 }
    };

    Console.WriteLine("Ages:");
    foreach (KeyValuePair<string, int> entry in ages)
    {
        Console.WriteLine($"{entry.Key}: {entry.Value}");
    }
}

}

`

Output

Fruits: Apple Banana Orange

Numbers: 10 20 30

Ages: A: 30 B: 25 C: 35

Limitations of the foreach Loop

**1. Non-Index Access: Unlike the for loop, the foreach loop doesn't provide an index variable that you can use to reference the position of the current element in the collection.

foreach (int num in numbers)

{
if (num == target)
{ return ???; // do not know the index of num
}
}

**2. Collection Modification: cannot remove or add elements to the collection while iterating with a foreach loop.

foreach(int num in marks)

{ // cannot modify array or collections like list and set.

// only changes num not

// the element

num = num * 2;

}

3. Foreach only iterates forward over the array in single steps

// cannot be converted to a foreach loop

for (int i = numbers.Length - 1; i > 0; i--)

{

Console.WriteLine(numbers[i]);

}

4. Performance Overhead: This may have performance drawbacks compared to traditional loops, especially with large datasets.

Advantages

**Note: Modifying the collection while iterating through it will result in a runtime error.

Difference Between for loop and foreach loop

Feature for Loop foreach Loop
Definition Execute the code written within a block until the defined condition becomes false. Iterates through each element in a collection or array automatically.
Iteration Can be iterated through both directions forward and backward Only Iterate in the forward direction.
Performance Can be more efficient since it doesn’t create a copy of the array. Slightly less efficient for large collections due to copying overhead.
Use-Case Best for scenarios requiring custom indexing, backward iteration, or performance optimization. Used to iterate from elements of collections.