0
0
C Sharp (C#)programming~5 mins

Foreach loop over collections in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A foreach loop helps you go through each item in a group one by one without worrying about counting or indexes.

When you want to read or use every item in a list of names.
When you need to print all elements in an array of numbers.
When you want to check or change each item in a collection like a list or set.
When you want to add up all values in a collection without missing any.
When you want to avoid mistakes from counting indexes manually.
Syntax
C Sharp (C#)
foreach (var item in collection)
{
    // use item here
}
The item is each element you get from the collection one by one.
You cannot change the collection size inside the foreach loop.
Examples
This prints each fruit name from the array.
C Sharp (C#)
string[] fruits = {"apple", "banana", "cherry"};
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit);
}
This prints each number doubled from the list.
C Sharp (C#)
List<int> numbers = new List<int> {1, 2, 3};
foreach (int number in numbers)
{
    Console.WriteLine(number * 2);
}
Sample Program

This program creates a list of colors and prints each color with a label using a foreach loop.

C Sharp (C#)
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> colors = new List<string> {"red", "green", "blue"};
        foreach (var color in colors)
        {
            Console.WriteLine($"Color: {color}");
        }
    }
}
OutputSuccess
Important Notes

Foreach loops are safer and easier than for loops when you just want to read items.

You cannot add or remove items from the collection while inside a foreach loop.

Foreach works with any collection that implements IEnumerable.

Summary

Foreach loops let you visit each item in a collection easily.

They avoid mistakes from counting indexes manually.

Use foreach when you want to read or process all items one by one.