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

foreach Loop

In this page:

  1. foreach Loop

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);
        }
    }
}
🔒

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.