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:
- 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:
- It is necessary to enclose the statements of the foreach loop in curly braces {}.
- Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
- In the loop body, you can use the loop variable you created rather than using an indexed array element.
Flow Diagram of 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); } }
OutputNumber 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}"); } } }
OutputFruits: 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
- 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. |
---|
Similar Reads
C# | Using foreach loop in arrays
C# language provides several techniques to read a collection of items. One of which is foreach loop. The foreach loop provides a simple, clean way to iterate through the elements of an collection or an array of items. One thing we must know that before using foreach loop we must declare the array or
4 min read
C# - Infinite Loop
Infinite Loop is a loop that never terminates or ends and repeats indefinitely. Or in other words, an infinite loop is a loop in which the test condition does not evaluate to false and the loop continues forever until an external force is used to end it. You can create an infinite loop: Using for lo
2 min read
C# Loops
Looping in a programming language is a way to execute a statement or a set of statements multiple times depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops. Loops are mainly divided into two categories
5 min read
C#- Nested loops
Nested loops are those loops that are present inside another loop. In C#, nesting of for, while, and do-while loops are allowed and you can also put any nested loop inside any other type of loop like in a for loop you are allowed to put nested if loop. for Loop: The functionality of for loop is quit
3 min read
C# | Performing Specified action on each element of Array
Array.ForEach(T[], Action<T>) Method is used to perform the specified action on each element of the specified array. Syntax: public static void ForEach<T> (T[] array, Action<T> action); Parameters: array: The one-dimensional, zero-based Array on whose elements the action is to be p
3 min read
C# - Break statement
In C#, the break statement is used to terminate a loop(for, if, while, etc.) or a switch statement on a certain condition. And after terminating the controls will pass to the statements that present after the break statement, if available. If the break statement exists in the nested loop, then it wi
4 min read
C# | How to perform a specified action on each element of the List
List<T>.ForEach(Action<T>) Method is used to perform a specified action on each element of the List<T>. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it a
2 min read
C# - continue Statement
In C#, the continue statement is used to skip over the execution part of the loop(do, while, for, or foreach) on a certain condition, after that, it transfers the control to the beginning of the loop. Basically, it skips its given statements and continues with the next iteration of the loop. Or in o
2 min read
C# Arrays
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
Your First C Program
Like in most of the programming languages, program to write the text "Hello, World!" is treated as the first program to learn in C. This step-by-step guide shows you how to create and run your first C program. Table of Content Setting Up Your EnvironmentCreating a Source Code FileNavigating to the S
5 min read