C# Foreach Loop - Complete Guide
Introduction to Foreach Loops
The foreach loop in C# provides a simple and elegant way to iterate through collections, arrays, and any type that implements the IEnumerable or IEnumerable
Unlike the for loop, foreach doesn’t require an index or knowledge of collection length. It is especially useful for read-only iteration through collections.
Basic Foreach Loop Syntax
The foreach loop works with arrays, lists, strings, and dictionaries:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int n in numbers)
Console.WriteLine(n);
List<string> names = new() { "Alice", "Bob", "Charlie" };
foreach (string name in names)
Console.WriteLine(name);
string text = "Hello";
foreach (char c in text)
Console.WriteLine(c);
Dictionary<string, int> ages = new()
{
{ "Alice", 25 }, { "Bob", 30 }
};
foreach (var kvp in ages)
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
}
1 2 3 4 5 Alice Bob Charlie H e l l o Alice: 25 Bob: 30
Foreach with Custom Collections
Any class that implements IEnumerable can be used in a foreach loop.
using System;
using System.Collections;
using System.Collections.Generic;
class NumberCollection : IEnumerable<int>
{
private int[] data = { 10, 20, 30 };
public IEnumerator<int> GetEnumerator()
{
foreach (var n in data)
yield return n;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
class Program
{
static void Main()
{
foreach (var n in new NumberCollection())
Console.WriteLine(n);
}
}
10 20 30
Limitations and Best Practices
Foreach loops cannot modify the collection during iteration.
The loop variable in foreach is read-only for value types.
For performance, use for loops when modifying collections or when index access is required.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var numbers = new List<int> { 1, 2, 3 };
// Safe read
foreach (var n in numbers)
Console.WriteLine(n);
// Modification requires for loop
for (int i = 0; i < numbers.Count; i++)
numbers[i] *= 2;
foreach (var n in numbers)
Console.WriteLine(n);
}
}
1 2 3 2 4 6