← Back to C# Course | Chapter 4: Control Flow | Lesson 6 of 7

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:

  1. foreach Loop
Syntax
csharp
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

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        string[] fruits = { "apple", "banana", "cherry" };

        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
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
  1. Modifying the collection inside a foreach, which throws InvalidOperationException.
  2. Trying to assign to the loop variable, which is read-only in foreach.
  3. Using foreach on a null collection, which throws NullReferenceException.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.