foreach Loop
A foreach loop visits every item in a collection one by one, like a teacher handing a sheet to each student in a row. You never have to count positions.
In this page:
Syntax
foreach (type item in collection)
{
// use item
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Modifying the collection inside a
foreach, which throwsInvalidOperationException. - Trying to assign to the loop variable, which is read-only in
foreach. - Using
foreachon a null collection, which throwsNullReferenceException.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: