DEV Community

Sabin Sim
Sabin Sim

Posted on

35. C# (foreach Loop in C#)

Full Runnable Code

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 lets you iterate over elements directly without managing indices.

If this is not clear:

  • you overuse for
  • you write unnecessary index logic
  • your code becomes less readable

This lesson is about understanding element-based iteration.


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 role of i is only this:

To access words[i]

We are not using i for logic.

We are using it as a tool to retrieve elements.

So structurally:

for = index-driven access


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 from words
Assign it to word
Execute the block

No index is required.


3. Step-by-Step Execution Flow

Array:

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

First iteration

word = "apple"
print
Enter fullscreen mode Exit fullscreen mode

Second iteration

word = "banana"
print
Enter fullscreen mode Exit fullscreen mode

Third iteration

word = "cherry"
print
Enter fullscreen mode Exit fullscreen mode

Then the loop ends.

Important:

Indexing still happens internally, but it is hidden from you.


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 model:

  • for → control the iteration
  • foreach → consume elements

5. When Should You Use foreach?

Use foreach when:

  • you do not need the index
  • you process all elements
  • the operation is read-only
  • no custom stepping logic is required

In short:

“Do the same operation for every element.”


6. Important Limitation

You cannot directly use an index inside foreach.

This is invalid:

Console.WriteLine(i);
Enter fullscreen mode Exit fullscreen mode

There is no i.


Modification Does Not Affect Original Data

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

Reason:

number is a copy of the element, not the original reference.

So the original array remains unchanged.


Final Summary

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


Learning Check

Consider this code:

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

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

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

Explain:

  1. What is the output order?
  2. How many times does the loop run?
  3. What determines the number of iterations?

Answer using execution flow, not just results.

Top comments (0)