foreach Loop
In this page:
foreach Loop
foreach iterates over every element of a collection without manual index tracking, working with any type that implements IEnumerable. It's the safest and most readable way to process arrays, lists, and other collections. You cannot modify the loop variable to skip items — use indexed access for that.
Note: Prefer foreach over for whenever you don't need the index.
Example: foreach Loop
using System;
class Program
{
static void Main(string[] args)
{
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: