In C#, Array.ForEach walks a typed array and runs your Action<T> once per element. Beginners often pass a lambda: x => Console.WriteLine(x).
It is a compact alternative to a foreach loop when the body is a single action. It does not return a new array—use ConvertAll when you need to transform elements.
This is a static member of System.Array. You call it with the class name, such as Array.ForEach(...). Arrays in C# have a fixed length after creation; use List<T> when the count must grow.
Syntax
Pass the array and an action. The action receives one element at a time.
C#
Array.ForEach(nums, x => Console.WriteLine(x));
Array.ForEach(names, PrintName);
Call
What it does
Array.ForEach(nums, x => Console.WriteLine(x))
Prints each int on its own line.
Array.ForEach(names, n => Console.Write(n + " "))
Prints names separated by spaces.
ForEach is static and works on T[]. A normal foreach loop is equally fine and sometimes clearer.
Library declarations
C#
public static void ForEach<T>(T[] array, Action<T> action);
Parameters
Parameter
Description
array
Required. The T[] to walk.
action
Required. Method or lambda that receives each element.
Return Value
Return Value
Description
void
No return value. The action runs for side effects.
C# Examples
Example 1 — Print Every Element
Use a lambda to write each int.
C#
using System;
class Program {
static void Main() {
int[] nums = { 10, 20, 30 };
Array.ForEach(nums, x => Console.WriteLine(x));
}
}
Output
10
20
30
How It Works
Action lambda.x => Console.WriteLine(x) runs per element.
Order preserved. Left-to-right visit.
No return. ForEach is for side effects like printing.
Same as foreach. A loop would print the same lines.
Example 2 — Pass a Method Group
Reuse a named method as the action.
C#
using System;
class Program {
static void Show(string s) {
Console.WriteLine("Item: " + s);
}
static void Main() {
string[] names = { "Ann", "Bob" };
Array.ForEach(names, Show);
}
}
Output
Item: Ann
Item: Bob
How It Works
Method group.Show matches Action<string>.
Readable. Named methods help when logic grows.
Two calls. Ann then Bob.
No inline noise. Main stays short.
Example 3 — Accumulate in an Outer Variable
Add numbers into a sum using a captured variable.
C#
using System;
class Program {
static void Main() {
int[] nums = { 1, 2, 3, 4 };
int sum = 0;
Array.ForEach(nums, x => sum += x);
Console.WriteLine("sum = " + sum);
}
}
Output
sum = 10
How It Works
Closure. The lambda updates sum outside.
Running total. 1+2+3+4 = 10.
Side effect. Still not returning a new array.
LINQ Sum. In richer code, nums.Sum() may be clearer.
Frequently Asked Questions
It runs an Action once for every element of a T[] array.
No. Use ConvertAll when you need mapped results.
Neither is required. ForEach is compact for one action; foreach is often clearer for multi-line bodies.
Yes. Pass a method group that matches Action<T>.
Remaining elements are not processed after the exception.