DEV Community

Sabin Sim
Sabin Sim

Posted on

29. C# (foreach Loop)

in C# — Full Code First

using System;

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

        Console.WriteLine("Using for loop:");
        for (int i = 0; i < words.Length; i++)
        {
            Console.WriteLine(words[i]);
        }

        Console.WriteLine();

        Console.WriteLine("Using foreach loop:");
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }

        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

0. The Real Goal of This Lesson

foreach removes index management
and lets you focus directly on the element.

If you misunderstand this:

  • You overuse for
  • You write unnecessary index logic
  • Your intent becomes less readable

This lesson is about execution model clarity.


1. What the for Loop Is Actually Doing

for (int i = 0; i < words.Length; i++)
{
    Console.WriteLine(words[i]);
}
Enter fullscreen mode Exit fullscreen mode

The only purpose of i here is:

To access words[i]

We are not using i for logic.

We are using it just to retrieve elements.

The index is a middleman.


2. Understanding the foreach Structure

foreach (string word in words)
{
    Console.WriteLine(word);
}
Enter fullscreen mode Exit fullscreen mode

Structure:

foreach (Type variable in Collection)
Enter fullscreen mode Exit fullscreen mode

Meaning:

Take each element inside words
Assign it to word
Execute the block

No index required.


3. Step-by-Step Execution Flow

Array:

["apple", "banana", "cherry"]
Enter fullscreen mode Exit fullscreen mode

First iteration

word = "apple"
Print

Second iteration

word = "banana"
Print

Third iteration

word = "cherry"
Print

Then stop.

Internally, indexing still happens.
But it is abstracted away.


4. for vs foreach — Structural Difference

Criteria for foreach
Focus Index Element
Index access Yes No
Readability Medium Higher
Use case When index control is needed When simple traversal is needed

Mental shift:

  • for = index-driven loop
  • foreach = element-driven loop

5. When Should You Use foreach?

Use foreach when:

  • You do not need the index
  • You simply process each element
  • The operation is read-only
  • The order does not need custom control

In other words:

“Perform the same action for every element.”


6. Important Limitation

You cannot directly access the index inside foreach.

This is invalid:

Console.WriteLine(i); // no index variable
Enter fullscreen mode Exit fullscreen mode

Also:

foreach (int number in numbers)
{
    number = number * 2; // does NOT modify original array
}
Enter fullscreen mode Exit fullscreen mode

The variable number is a copy.

The original array remains unchanged.

This is a critical distinction.


Final Summary

foreach is the simplest way to iterate over a collection
when you only need the element, not the index.


Learning Check (One Question)

What is the output of this code?

int[] numbers = { 1, 2, 3 };

foreach (int number in numbers)
{
    Console.WriteLine(number);
}

Console.WriteLine("End");
Enter fullscreen mode Exit fullscreen mode

Answer precisely:

  1. What is the output order?
  2. How many iterations occur?
  3. What determines the number of iterations?

If you can explain this in terms of execution flow,
you understand foreach structurally.

Top comments (0)