DevAcademia
C++C#CPythonJava
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction

Loading Cs tutorial…

Loading content
C# BasicsTopic 32 of 55
←PreviousPrevNextNext→

C# Foreach Loop - Complete Guide

Introduction to Foreach Loops

The foreach loop in C# provides a simple and elegant way to iterate through collections, arrays, and any type that implements the IEnumerable or IEnumerable interface. It automatically handles iteration, making code cleaner and less error-prone.

Unlike the for loop, foreach doesn’t require an index or knowledge of collection length. It is especially useful for read-only iteration through collections.

Basic Foreach Loop Syntax

The foreach loop works with arrays, lists, strings, and dictionaries:

Example
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        foreach (int n in numbers)
            Console.WriteLine(n);

        List<string> names = new() { "Alice", "Bob", "Charlie" };
        foreach (string name in names)
            Console.WriteLine(name);

        string text = "Hello";
        foreach (char c in text)
            Console.WriteLine(c);

        Dictionary<string, int> ages = new()
        {
            { "Alice", 25 }, { "Bob", 30 }
        };
        foreach (var kvp in ages)
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
    }
}
Output
1
2
3
4
5
Alice
Bob
Charlie
H
e
l
l
o
Alice: 25
Bob: 30

Foreach with Custom Collections

Any class that implements IEnumerable can be used in a foreach loop.

Example
using System;
using System.Collections;
using System.Collections.Generic;

class NumberCollection : IEnumerable<int>
{
    private int[] data = { 10, 20, 30 };

    public IEnumerator<int> GetEnumerator()
    {
        foreach (var n in data)
            yield return n;
    }
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

class Program
{
    static void Main()
    {
        foreach (var n in new NumberCollection())
            Console.WriteLine(n);
    }
}
Output
10
20
30

Limitations and Best Practices

Foreach loops cannot modify the collection during iteration.

The loop variable in foreach is read-only for value types.

For performance, use for loops when modifying collections or when index access is required.

Example
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var numbers = new List<int> { 1, 2, 3 };

        // Safe read
        foreach (var n in numbers)
            Console.WriteLine(n);

        // Modification requires for loop
        for (int i = 0; i < numbers.Count; i++)
            numbers[i] *= 2;

        foreach (var n in numbers)
            Console.WriteLine(n);
    }
}
Output
1
2
3
2
4
6
Test your knowledge: C# Foreach Loop - Complete Guide
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
C# BasicsTopic 32 of 55
←PreviousPrevNextNext→