Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  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 3173
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
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,939 views
  • 2
    Error-An error occurred while processing your request in .… 11,281 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 236 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,464 views
  • 5
    Complete Guide to Creating a Registration Form in HTML/CSS 4,218 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,507 views
  • 7
    Mastering JavaScript Error Handling with Try, Catch, and F… 162 views

On this page

🎯

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 12905 views
  • Convert HTML String To Image In C# 11517 views
  • The report definition is not valid or is not supported by th… 10886 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9877 views
  • Get IP address using c# 8703 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 | 1770
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
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • 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