C# foreach Loop
The C# foreach loop executes a block of statements once for every element in an array or collection. It is commonly used when you need to read or process all items without managing an index manually.
A foreach loop works with arrays and types that can be enumerated, including List<T>, Dictionary<TKey, TValue>, strings, sets, and many other .NET collections.
C# foreach Loop Syntax
foreach (dataType item in collection)
{
// Statements that use item
}
dataTypeis the type of each element in the collection. You can often usevarand let the compiler infer it.itemis the local variable representing the current element.collectionis the array or enumerable collection being traversed.
The loop starts with the first element, executes the loop body, and then moves to the next element. It stops after every element has been processed or when control leaves the loop through a statement such as break or return.
C# foreach on String Array
In the following example, we use foreach to print the modified string to console for each element in the array.
Program.cs
using System;
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
string[] names = {"Ducati", "Honda", "Royal Enfield"};
foreach(var name in names){
Console.WriteLine("Buy "+name);
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Buy Ducati
Buy Honda
Buy Royal Enfield
During each iteration, name refers to one string from the names array. The array order is preserved, so the values are printed in the same order in which they were declared.
C# foreach on List Items
Following examples demonstrates the usage of foreach loop on List elements. We just print them. You can do much more on each element of the list based on your use-case requirements.
Program.cs
using System;
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
var names = new List<string>() {"Ducati", "Honda", "Royal Enfield"};
foreach(var name in names){
Console.WriteLine(name);
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Ducati
Honda
Royal Enfield
The compiler infers that name is a string because the collection is a List<string>. Writing foreach (string name in names) would produce the same result.
C# foreach with a Dictionary
You can use foreach to access each of the item in Dictionary. In the following example, we access each item of the dictionary, and then get the key and values separately.
Program.cs
using System;
using System.Collections.Generic;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Dictionary<int, string> dict1 = new Dictionary<int, string>(){
{1, "Tesla"},
{2, "Honda"},
{3, "Toyota"}
};
foreach(KeyValuePair<int, string> item in dict1) {
Console.WriteLine(item.Key+" - "+item.Value);
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
1 - Tesla
2 - Honda
3 - Toyota
Each dictionary entry is represented by a KeyValuePair<int, string>. Its Key and Value properties provide access to the two parts of the entry.
Using Key-Value Deconstruction in a C# Dictionary foreach Loop
Modern C# also supports deconstructing a dictionary entry into separate key and value variables. This can make the loop easier to read when both values are needed.
var vehicleNames = new Dictionary<int, string>
{
{ 1, "Tesla" },
{ 2, "Honda" },
{ 3, "Toyota" }
};
foreach (var (id, vehicleName) in vehicleNames)
{
Console.WriteLine($"{id} - {vehicleName}");
}
Iterating Through Characters in a C# String
A string can be enumerated as a sequence of char values. Therefore, foreach can process one character at a time.
string word = "CSharp";
foreach (char character in word)
{
Console.WriteLine(character);
}
Output
C
S
h
a
r
p
Using break and continue in a C# foreach Loop
The break statement ends the loop immediately. The continue statement skips the remaining statements for the current element and proceeds with the next element.
int[] numbers = { 2, 5, 8, 11, 14 };
foreach (int number in numbers)
{
if (number == 5)
{
continue;
}
if (number == 11)
{
break;
}
Console.WriteLine(number);
}
Output
2
8
The value 5 is skipped by continue. When the loop reaches 11, break stops the loop, so 11 and 14 are not printed.
Can a C# foreach Iteration Variable Be Changed?
The iteration variable itself cannot be assigned a different value inside the loop. For example, assigning a new value directly to number in foreach (int number in numbers) causes a compile-time error.
When a collection contains reference-type objects, you can usually update writable properties of the current object. However, assigning another object to the iteration variable is not allowed.
var products = new List<Product>
{
new Product { Name = "Keyboard", InStock = false },
new Product { Name = "Mouse", InStock = false }
};
foreach (Product product in products)
{
product.InStock = true;
}
class Product
{
public string Name { get; set; } = string.Empty;
public bool InStock { get; set; }
}
Avoid Modifying a Collection During foreach Enumeration
Do not add or remove elements from most collections while a foreach loop is enumerating them. Collections such as List<T> generally throw an InvalidOperationException when their structure changes during enumeration.
When items must be removed, consider one of these approaches:
- Use a suitable method such as
List<T>.RemoveAll. - Iterate over a copy of the collection.
- Use a reverse
forloop when removing list elements by index. - Create a new filtered collection instead of changing the original during enumeration.
C# foreach Loop Compared with a for Loop
| Requirement | Preferred loop |
|---|---|
| Process every element without using its position | foreach |
| Access an element by numeric index | for |
| Move through an array or list in reverse order | for |
| Use a readable loop over a dictionary or set | foreach |
| Replace array or list elements by index | for |
Use foreach when the operation depends on each value rather than its index. Use for when the index, direction, or direct replacement of indexed elements is part of the operation.
C# foreach Loop Editorial Checklist
- Confirm that the source value is an array or enumerable collection.
- Use an iteration variable type that matches the collection element type, or use
var. - Do not assign a new value directly to the iteration variable.
- Avoid adding or removing collection elements during enumeration.
- Use
breakonly when the remaining elements do not need to be processed. - Choose a
forloop instead when the element index is required.
Frequently Asked Questions About C# foreach
Does a C# foreach loop provide the current index?
No. A standard foreach loop provides the current element but not its numeric index. Use a separate counter or a for loop when the index is required.
Can foreach iterate through a C# string?
Yes. A string can be enumerated as a sequence of char values, so each iteration receives one character.
Can foreach iterate through a C# Dictionary?
Yes. Each iteration receives a key-value pair. You can access the entry through its Key and Value properties or deconstruct it into separate variables.
Can a foreach loop be stopped early?
Yes. Use break to leave the loop immediately. A return statement can also leave the containing method, while continue skips only the current iteration.
Summary of C# foreach Usage
In this C# Tutorial, we learned how to use the foreach loop to iterate over arrays, lists, dictionaries, and strings. We also covered dictionary deconstruction, break, continue, iteration-variable restrictions, collection modification, and the choice between foreach and for.
TutorialKart.com