- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Arithmetic Operators
- C# - Assignment Operators
- C# - Relational Operators
- C# - Logical Operators
- C# - Bitwise Operators
- C# - Miscellaneous Operators
- C# - Operators Precedence
- C# Conditional Statements
- C# - Decision Making
- C# - If
- C# - If Else
- C# - Nested If
- C# - Switch
- C# - Nested Switch
- C# - Switch Expressions
- C# Control Statements
- C# - Loops
- C# - For Loop
- C# - While Loop
- C# - Do While Loop
- C# - Nested Loops
- C# - Break
- C# - Continue
- C# - Foreach Loop
- C# - Goto Statement
- C# OOP & Data Handling
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - LINQ
- C# - IEnumerable vs IEnumerator
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Tasks and Parallel Programming
- C# - Multithreading
- C# - Extension Methods
Foreach Loop in C#
C# provides the foreach loop to easily go through all elements in a collection like an array or list. It helps us read each element one by one without using counters or indexes. In this chapter, we will learn what a foreach loop is in C# with examples.
Foreach Loop in C#
The foreach loop in C# is a control flow statement that traverses all elements in a collection without using an index variable or counter. It automatically moves from one element to the next element until all elements have been processed.
Flow Diagram of foreach Loop
Following is the diagram that shows how the foreach loop works in C#.
Syntax of Foreach Loop
Below is the syntax for decalring the foreach loop in C# −
foreach (dataType variableName in collection_name){
// statements to execute
}
Here in this syntax −
- dataType is the type of elements in the collection, for example int or string.
- variableName is a temporary variable for the current element.
- in is the keyword that connects the variable to the collection.
- collection is the array, list, or collection to iterate through.
- Loop body is the code inside { } that runs for each element.
Example
In this example, we will iterate through an array of numbers using a foreach loop and print each number.
using System;
class Program {
static void Main(){
int[] numbers = { 10, 20, 30, 40, 50 };
foreach (int num in numbers){
Console.WriteLine($"Number: {num}");
}
}
}
In the above program, int is the data type, num is the loop variable, and numbers is the array being iterated. The output of the program is shown below −
Number: 10 Number: 20 Number: 30 Number: 40 Number: 50
Examples of Foreach Loop in C#
Let's see some examples of the foreach loop in C# to understand how we can iterate through arrays and lists and work with each element.
Example 1: Using Foreach with Arrays
In this example, we will access the elements of an array using a foreach loop and print them. Each number in the array is automatically assigned to the loop variable without worrying about its index.
using System;
class Program {
static void Main(){
// Define an array of numbers
int[] numbers = { 1, 2, 3, 4, 5 };
// Loop through each number and print it
foreach (int number in numbers){
Console.WriteLine(number);
}
}
}
Following is the output of the above program −
1 2 3 4 5
Example 2: Nested Foreach Loops
In this example, we will use a nested foreach loop to iterate through a 2D array (array of arrays). The outer loop goes through each row, and the inner loop goes through each element in that row.
using System;
class Program {
static void Main(){
// Define array of arrays
int[][] matrix = new int[][]{
new int[] {1, 2},
new int[] {3, 4},
new int[] {5, 6}
};
// Loop through each row and print its elements
foreach (int[] row in matrix){
foreach (int item in row){
Console.Write(item + " ");
}
Console.WriteLine(); // Move to the next line after each row
}
}
}
Below is the output of the above program which displays the elements of each row in the matrix.
1 2 3 4 5 6
Example 3: Using Foreach with Lists
In this example, we are going to loop through a list of fruits. Each fruit in the fruits list is displayed on a separate line automatically by the loop.
using System;
using System.Collections.Generic;
class Program {
static void Main(){
// Create a list containing fruit names
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
// Display all fruits from the list
foreach (string fruit in fruits){
Console.WriteLine(fruit);
}
}
}
Following is the output which displays the elements of the list.
Apple Banana Orange
Example 4: Using Foreach with Dictionaries
In this example, we will use a foreach loop to go through a dictionary that stores student IDs as keys and student names as values. The loop will visit each key-value pair in the dictionary and print both the student ID and the name.
using System;
using System.Collections.Generic;
class Program {
static void Main(){
// Create a dictionary with student IDs and names
Dictionary<int, string> students = new Dictionary<int, string> {
{ 1, "John" },
{ 2, "Sarah" },
{ 3, "Mike" }
};
foreach (KeyValuePair<int, string> student in students){
Console.WriteLine($"ID: {student.Key}, Name: {student.Value}");
}
}
}
Below you can see the output which displays both the student ID and name.
ID: 1, Name: John ID: 2, Name: Sarah ID: 3, Name: Mike
Limitations and Common Errors
The foreach loop is easy to use, but there are some rules and limitations that we should know to avoid mistakes. To understand them better, let's go through each of them with examples below.
Loop Variable is Read-Only
The variable used in a foreach loop cannot be reassigned inside the loop. We can read its value but we cannot change the variable itself. This is especially important for primitive data types like int, double, etc. For example −
using System;
class Program {
static void Main(){
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers){
num = num * 2; // Error: cannot reassign loop variable
Console.WriteLine(num); // Allowed: reading value
}
}
}
When we try to assign a new value to num, we will get an error as shown in the output below −
Compilation error (line 11, col 13): Cannot assign to 'num' because it is a 'foreach iteration variable'
Cannot Modify the Collection While Iterating
We cannot add or remove elements from a collection while iterating through it using foreach loop. Doing so will throw a runtime error (InvalidOperationException). This limitation is about the collection structure, not the loop variable. For example -
using System;
using System.Collections.Generic;
class Program {
static void Main(){
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (int num in numbers){
if (num == 3)
numbers.Remove(num); // InvalidOperationException
}
}
}
Here's the output which clearly shows an error that occurs when we try to modify a collection while iterating through it.
Unhandled exception. System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.Collections.Generic.List`1.Enumerator.MoveNext() at Program.Main() Command terminated by signal 6
Can Modify Object Properties
Even though the loop variable is read-only, we can modify the properties of reference type objects (like class objects) in a collection. This is useful when working with lists of objects.
Here's an example where we create a list of Person objects and increase the age of each person by 1 inside the loop, without reassigning or changing the person variable itself.
using System;
using System.Collections.Generic;
class Person {
public string Name { get; set; }
public int Age { get; set; }
}
class Program {
static void Main(){
// Create a list of people
List<Person> people = new List<Person> {
new Person { Name = "John", Age = 30 },
new Person { Name = "Sarah", Age = 25 }
};
// Update age of each person by 1
foreach (Person person in people) {
person.Age += 1; // Modifying object property is allowed
}
// Print updated ages
foreach (Person person in people){
Console.WriteLine($"{person.Name}: {person.Age}");
}
}
}
Below output displays the updated ages of each person after increasing their age by 1 inside the loop.
John: 31 Sarah: 26
Foreach Only Iterates Forward in Single Steps
A foreach loop always moves forward through the collection, one element at a time. We cannot iterate backward or jump multiple elements.
using System;
class Program {
static void Main(){
int[] numbers = { 10, 20, 30, 40, 50 };
// Attempting backward iteration using foreach is not possible
foreach (int num in numbers){
// Cannot access previous elements directly
Console.WriteLine(num);
}
}
}
Following is the output of the above program, which displays the elements after forward traversal.
10 20 30 40 50
Non-Index Access
Foreach loop does not provide the index of each element automatically. If we need the position of an element, we must use a separate counter. For example −
using System;
class Program {
static void Main(){
string[] names = { "Alice", "Bob", "Charlie" };
int index = 0;
foreach (string name in names){
Console.WriteLine($"Index: {index}, Name: {name}");
index++;
}
}
}
Following is the output of the above program which shows each element with its index.
Index: 0, Name: Alice Index: 1, Name: Bob Index: 2, Name: Charlie
Using break and continue in a Foreach Loop
Sometimes, we don't want the loop to go through all the elements. We may want to stop the loop early or skip some items based on certain conditions. In C#, we can control this using the keywords break and continue.
We'll see examples for both −
Break Statement with foreach loop
The break statement immediately stops the loop when a specific condition becomes true. After break executes, the loop ends, and the program continues with the next statements outside the loop.
Example
In this example, we print numbers from the array. When the number reaches 15, the break statement runs, immediately stopping the loop, so any numbers after 15 are not printed.
using System;
class Program {
static void Main(){
// Define an array of numbers
int[] numbers = { 5, 10, 15, 20 };
// Loop through each number and stop when number is 15
foreach (int n in numbers){
if (n == 15)
break; // Exit the loop when n is 15
Console.WriteLine(n);
}
}
}
Following is the output of the program which displays the numbers before the loop is stopped by the break statement.
5 10
Continue Statement with foreach loop
The continue statement skips the current iteration and moves to the next element in the collection. It doesn't stop the loop completely.
Example
In this example, the loop checks each number in the array. When it reaches 15, the continue statement skips printing 15 and continues printing the remaining numbers
using System;
class Program {
static void Main(){
// Define an array of numbers
int[] numbers = { 5, 10, 15, 20 };
// Loop through each number and skip printing 15
foreach (int n in numbers){
if (n == 15)
continue; // Skip printing n = 15
Console.WriteLine(n);
}
}
}
After running the program, the output shows all the numbers from the array except 15.
5 10 20
Conclusion
In this chapter, we learned about the foreach loop in C#. It allows us to traverse arrays, lists, or any collection without using an index or counter. We also saw how to control the loop with break and continue, and understood its main limitations.