Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular
    • Asp.net Core
    • C
    • C#
    • DotNet
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • Security
    • SQL Server
    • TypeScript
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
    • SEO Analyzer
    • Background Remover
  1. Home
  2. Blog
  3. C#
  4. Mastering the foreach Loop in C#: A Complete Guide with Examples

Mastering the foreach Loop in C#: A Complete Guide with Examples

Date- Dec 09,2023

Updated Feb 2026

3131

csharp foreach loop

Introduction to the foreach Loop

The foreach loop in C# is designed to simplify the process of iterating through collections such as arrays, lists, and other enumerable types. Unlike traditional loops, which require manual indexing, the foreach loop abstracts away the complexity, allowing developers to focus on the logic of their code rather than the mechanics of iteration.

In real-world applications, the foreach loop is invaluable when dealing with data structures that require processing of each element, such as displaying user data, processing items in a shopping cart, or iterating over records in a database. Its straightforward syntax enhances code readability and reduces the likelihood of errors associated with manual index management.

Basic Syntax of the foreach Loop

The basic syntax of the foreach loop is as follows:

foreach (var item in collection) {
    // code block
}

Here, item represents the current element in the iteration, while collection is the array or collection being traversed. The loop continues until all elements in the collection have been processed.

Example 1: Simple Iteration through an Array

using System;

public class Program {
    public static void Main() {
        Console.WriteLine("foreach loop Example!");
        string[] names = new string[5] { "Shubham", "Rahul", "Mohit", "Anmol", "Sham" };
        foreach (var name in names) {
            Console.WriteLine("Name - " + name);
        }
    }
}

The output of this code will be:

foreach loop Example!
Name - Shubham
Name - Rahul
Name - Mohit
Name - Anmol
Name - Sham

Example 2: Conditional Processing

using System;

public class Program {
    public static void Main() {
        Console.WriteLine("foreach loop Example!");
        string[] names = new string[] { "Shubham Batra" };
        foreach (var name in names) {
            if (name == "Shubham Batra") {
                Console.WriteLine("Hey - " + name);
            }
        }
    }
}

The output will be:

foreach loop Example!
Hey - Shubham Batra

Iterating through Collections

In addition to arrays, the foreach loop can be used to iterate through any collection that implements the IEnumerable interface. This includes data structures like lists, dictionaries, and sets. The ability to loop through these collections seamlessly makes the foreach loop an essential tool for developers.

Example 3: Iterating through a List

using System;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        List fruits = new List { "Apple", "Banana", "Cherry" };
        foreach (var fruit in fruits) {
            Console.WriteLine("Fruit: " + fruit);
        }
    }
}

The output will be:

Fruit: Apple
Fruit: Banana
Fruit: Cherry

Using foreach with Dictionaries

The foreach loop can also be used to iterate through key-value pairs in a dictionary. This is particularly useful when you need to access both the key and the value during iteration.

Example 4: Iterating through a Dictionary

using System;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        Dictionary scores = new Dictionary {
            { "Alice", 90 },
            { "Bob", 85 },
            { "Charlie", 92 }
        };
        foreach (var entry in scores) {
            Console.WriteLine(entry.Key + " scored " + entry.Value);
        }
    }
}

The output will be:

Alice scored 90
Bob scored 85
Charlie scored 92

Edge Cases & Gotchas

While the foreach loop is generally straightforward, there are some edge cases and gotchas to be aware of:

  • Modification during Iteration: Modifying the collection you are iterating over (e.g., adding or removing elements) can lead to runtime exceptions. It is best to create a copy of the collection if you need to modify it during iteration.
  • Null Collections: If the collection is null, attempting to use a foreach loop will throw a NullReferenceException. Always ensure that the collection is initialized before iterating.
  • Value Types vs Reference Types: When iterating over a collection of value types, be aware of boxing and unboxing, which can affect performance.

Performance & Best Practices

To maximize the efficiency of your foreach loops, consider the following best practices:

  • Use foreach for Read-Only Operations: If you do not need to modify the collection, prefer foreach over for loops for better readability.
  • Avoid Modifying Collections: As mentioned earlier, avoid modifying the collection during iteration to prevent exceptions. If you need to filter or transform elements, consider using LINQ.
  • Consider Parallel Processing: For large collections, consider using parallel processing techniques, such as PLINQ, to improve performance.
  • Be Mindful of Collection Type: The performance of foreach can vary based on the type of collection being iterated. For example, lists generally perform better than arrays when it comes to dynamic resizing and element access.

Conclusion

The foreach loop is an essential tool in C# that simplifies the process of iterating through collections and arrays. By understanding its syntax, capabilities, and best practices, you can write cleaner, more efficient code.

  • The foreach loop provides a simple syntax for iteration.
  • It can be used with arrays, lists, dictionaries, and other collections.
  • Be cautious of modifying collections during iteration.
  • Follow best practices to enhance performance and readability.

S
Shubham Saini
Programming author at Code2Night โ€” sharing tutorials on ASP.NET, C#, and more.
View all posts โ†’

Related Articles

Introduction to C# Programming: Your First Steps in Software Development
Mar 08, 2026
Understanding Destructors in C#: A Complete Guide with Examples
Dec 09, 2023
Understanding Method Parameters in C#: A Complete Guide
Dec 09, 2023
Complete Guide to Lists in C#: Examples and Best Practices
Dec 09, 2023
Previous in C#
Mastering While Loops in C#: A Complete Guide with Examples
Next in C#
If Else Statement

Comments

Contents

๐ŸŽฏ

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • Zoom C# Wrapper Integration 12898 views
  • Convert HTML String To Image In C# 11456 views
  • The report definition is not valid or is not supported by th… 10794 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9756 views
  • Get IP address using c# 8616 views
View all C# posts โ†’

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
  • SEO Analyzer
By Language
  • Angular
  • Asp.net Core
  • C
  • C#
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ยท  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor