0
0
CsharpHow-ToBeginner · 3 min read

How to Use foreach Loop in C# - Simple Guide

In C#, use the foreach loop to go through each item in a collection like an array or list. It automatically assigns each element to a variable, letting you run code for every item without managing indexes.
📐

Syntax

The foreach loop syntax in C# is simple and reads like natural language. It has three parts:

  • Type: The data type of each element in the collection.
  • Variable: A temporary name for the current element during each loop cycle.
  • Collection: The array, list, or any enumerable collection you want to loop through.

The loop runs once for every element in the collection.

csharp
foreach (type variable in collection)
{
    // code to execute for each element
}
💻

Example

This example shows how to use foreach to print each fruit name from a string array.

csharp
using System;

class Program
{
    static void Main()
    {
        string[] fruits = { "Apple", "Banana", "Cherry" };

        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
Output
Apple Banana Cherry
⚠️

Common Pitfalls

Some common mistakes when using foreach loops include:

  • Trying to modify the collection inside the loop, which can cause errors.
  • Attempting to change the loop variable itself, which is read-only.
  • Using foreach on a null collection, which throws an exception.

Always ensure the collection is not null and avoid modifying it during iteration.

csharp
/* Wrong: Modifying collection inside foreach */
// List<int> numbers = new List<int> {1, 2, 3};
// foreach (int num in numbers)
// {
//     numbers.Add(num + 10); // This causes runtime error
// }

/* Correct: Modify collection outside the loop or use for loop */
using System.Collections.Generic;

List<int> numbers = new List<int> {1, 2, 3};
List<int> newNumbers = new List<int>();
foreach (int num in numbers)
{
    newNumbers.Add(num + 10);
}
📊

Quick Reference

Remember these tips when using foreach loops:

  • Use foreach to read elements easily without index management.
  • The loop variable is read-only; do not assign new values to it.
  • Do not change the collection inside the loop to avoid errors.
  • Works with any collection implementing IEnumerable.

Key Takeaways

Use foreach to iterate over collections simply without managing indexes.
The loop variable in foreach is read-only and cannot be changed inside the loop.
Avoid modifying the collection while iterating with foreach to prevent errors.
Foreach works with arrays, lists, and any IEnumerable collections.
Always check that the collection is not null before using foreach.