When you have a collection of items โ an array, a list, or anything iterable โ and you want to do something with each item, foreach is your friend. No counters, no index variables, just the item.
The foreach Loop
foreach (var item in collection) โ read that aloud: "for each item in the collection, do this." Clean and simple.
using System;
class Program {
static void Main() {
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
}
}
Try it Yourself โ
Iterating Arrays and Collections
Works on arrays, List, Dictionary, and anything that implements IEnumerable. You don't need to know the length โ foreach figures it out.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List numbers = new List { 10, 20, 30, 40 };
foreach (int num in numbers) {
Console.WriteLine(num);
}
}
}
Try it Yourself โ
Read-Only Iteration
You can't modify the collection inside a foreach โ no adding, no removing items. But you can read and use each item however you like.
using System;
class Program {
static void Main() {
int[] nums = { 1, 2, 3, 4, 5 };
int sum = 0;
foreach (int n in nums) {
sum += n;
}
Console.WriteLine("Sum: " + sum);
}
}
Try it Yourself โ
foreach with var
Use var instead of the explicit type โ C# infers the type from the collection. Saves typing and keeps code cleaner.
using System;
class Program {
static void Main() {
double[] prices = { 9.99, 15.49, 3.99 };
foreach (var price in prices) {
Console.WriteLine("$" + price);
}
}
}
Try it Yourself โ