C# foreach Loop

Last Updated : 20 Apr, 2026

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:

C#
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); 
        }
    }
}

Output
G
e
e
k

Syntax of foreach Loop

foreach (type variableName in collection)

{
// Code to execute for each element
}

Parameters:

  • data_type: The type of elements in the collection (e.g., int, string, etc.).
  • variable_name: A temporary variable that holds the current element during each iteration.
  • collection: The array or collection being iterated over.

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:

  • Curly braces {} are optional when the loop contains a single statement, but they are recommended for better readability and maintainability.
  • Declare a variable and use in with the collection (no index needed).
  • Use the loop variable directly instead of array indexing.

Flow Diagram of foreach Loop

Foreach-Loop
Flow Diagram of foreach Loop

Example: This example demonstrates the foreach loop in C#, iterating over an array to count the number of male and female elements.

C#
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: 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)
{ // index not available here
}
}

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

  • It provides a clean and concise syntax for iterating over collections without manual indexing.
  • It enhances code readability by eliminating complex loop constructs.
  • It reduces the risk of off-by-one errors common in traditional loops.
  • It handles index management internally, simplifying the iteration process.
  • It results in cleaner code that is easier to maintain and debug

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.

Comment

Explore