Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# | Performing Specified action on each element of Array
Next article icon

C# foreach Loop

Last Updated : 03 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

foreach loop in C# is a special type of loop designed to iterate through collections like arrays, lists, and other enumerable data types. It simplifies the process of accessing each element in a collection without the need for manual indexing. This is useful when performing operations on every element of an array or collection without worrying about the indexes.

Example 1:

C#
// C# Program to iterate Through  // an Array Using foreach loop using System;  class Geeks {     static void Main(string[] args)     {         char[] arr = { 'G', 'e', 'e', 'k' };          // Using foreach to print          // each character in the array         foreach(char ch in arr)         {            Console.WriteLine(ch);          }     } } 

Output
G e e k 

Syntax of foreach Loop

foreach (data_type variable_name in collection)

{
// Code to execute for each element
}

Parameters:

  • data_type: The type of elements in the collection (e.g., int, string, etc.).
  • variable_name: A temporary variable that holds the current element during each iteration.
  • collection: The array or collection being iterated over.

The foreach loop uses the in keyword to iterate over each item in the specified collection. On each iteration, it selects an item from the collection and stores it in the variable defined. The loop continues until all elements have been processed.

Important Points:

  • It is necessary to enclose the statements of the foreach loop in curly braces {}.
  • Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
  • In the loop body, you can use the loop variable you created rather than using an indexed array element.

Flow Diagram of foreach Loop

Foreach-Loop

Example 2:

C#
// Counting Elements Based on Conditions using System;  class Geeks  {   static void Main(string[] args)     {         char[] gender = { 'm', 'f', 'm', 'm', 'f' };         int maleCount = 0, femaleCount = 0;          // Counting males and females using foreach         foreach(char g in gender)         {             if (g == 'm')                 maleCount++;             else if (g == 'f')                 femaleCount++;         }          Console.WriteLine("Number of males: " + maleCount);         Console.WriteLine("Number of females: "         + femaleCount);     } } 

Output
Number of males: 3 Number of females: 2 

Example 3: This example demonstrating the foreach loop in C#, the iteration of different collections (arrays, lists, and dictionaries):

C#
using System; using System.Collections.Generic;  class Geeks {     public static void Main()     {         // Iterating through an array of strings         string[] f = { "Apple", "Banana", "Orange" };          Console.WriteLine("Fruits:");          // Iterating through the array and printing each fruit         foreach (string fruit in f)         {             Console.WriteLine(fruit);           }         Console.WriteLine();          // Iterating through a list of integers         List<int> n = new List<int> { 10, 20, 30 };          Console.WriteLine("Numbers:");         foreach (int number in n)         {             Console.WriteLine(number);           }         Console.WriteLine();          // Iterating through a dictionary         Dictionary<string, int> ages = new Dictionary<string, int>         {             { "A", 30 },             { "B", 25 },             { "C", 35 }         };          Console.WriteLine("Ages:");         foreach (KeyValuePair<string, int> entry in ages)         {             Console.WriteLine($"{entry.Key}: {entry.Value}");         }     } } 

Output
Fruits: Apple Banana Orange  Numbers: 10 20 30  Ages: A: 30 B: 25 C: 35 

Limitations of the foreach Loop

1. Non-Index Access: Unlike the for loop, the foreach loop doesn’t provide an index variable that you can use to reference the position of the current element in the collection.

foreach (int num in numbers)

{
if (num == target)
{ return ???; // do not know the index of num
}
}

2. Collection Modification: cannot remove or add elements to the collection while iterating with a foreach loop.

foreach(int num in marks)

{ // cannot modify array or collections like list and set.

// only changes num not

// the element

num = num * 2;

}

3. Foreach only iterates forward over the array in single steps

// cannot be converted to a foreach loop

for (int i = numbers.Length – 1; i > 0; i–)

{

Console.WriteLine(numbers[i]);

}

4. Performance Overhead: This may have performance drawbacks compared to traditional loops, especially with large datasets.

Advantages

  • It provides a clean and concise syntax for iterating over collections without manual indexing.
  • It enhances code readability by eliminating complex loop constructs.
  • It reduces the risk of off-by-one errors common in traditional loops.
  • It handles index management internally, simplifying the iteration process.
  • It results in cleaner code that is easier to maintain and debug

Note: Modifying the collection while iterating through it will result in a runtime error.

Difference Between for loop and foreach loop

Feature

for Loop

foreach Loop

Definition

Execute the code written within a block until the defined condition becomes false.

Iterates through each element in a collection or array automatically.

Iteration

Can be iterated through both directions forward and backward

Only Iterate in the forward direction.

Performance

Can be more efficient since it doesn’t create a copy of the array.

Slightly less efficient for large collections due to copying overhead.

Use-Case

Best for scenarios requiring custom indexing, backward iteration, or performance optimization.

Used to iterate from elements of collections.



Next Article
C# | Performing Specified action on each element of Array
author
ankita_saini
Improve
Article Tags :
  • C#
  • CSharp-ControlFlow
  • CSharp-Decision Making

Similar Reads

  • C# | Using foreach loop in arrays
    C# language provides several techniques to read a collection of items. One of which is foreach loop. The foreach loop provides a simple, clean way to iterate through the elements of an collection or an array of items. One thing we must know that before using foreach loop we must declare the array or
    4 min read
  • C# - Infinite Loop
    Infinite Loop is a loop that never terminates or ends and repeats indefinitely. Or in other words, an infinite loop is a loop in which the test condition does not evaluate to false and the loop continues forever until an external force is used to end it. You can create an infinite loop: Using for lo
    2 min read
  • C# Loops
    Looping in a programming language is a way to execute a statement or a set of statements multiple times depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops. Loops are mainly divided into two categories
    5 min read
  • C#- Nested loops
    Nested loops are those loops that are present inside another loop. In C#, nesting of for, while, and do-while loops are allowed and you can also put any nested loop inside any other type of loop like in a for loop you are allowed to put nested if loop. for Loop: The functionality of for loop is quit
    3 min read
  • C# | Performing Specified action on each element of Array
    Array.ForEach(T[], Action<T>) Method is used to perform the specified action on each element of the specified array. Syntax: public static void ForEach<T> (T[] array, Action<T> action); Parameters: array: The one-dimensional, zero-based Array on whose elements the action is to be p
    3 min read
  • C# - Break statement
    In C#, the break statement is used to terminate a loop(for, if, while, etc.) or a switch statement on a certain condition. And after terminating the controls will pass to the statements that present after the break statement, if available. If the break statement exists in the nested loop, then it wi
    4 min read
  • C# | How to perform a specified action on each element of the List
    List<T>.ForEach(Action<T>) Method is used to perform a specified action on each element of the List<T>. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it a
    2 min read
  • C# - continue Statement
    In C#, the continue statement is used to skip over the execution part of the loop(do, while, for, or foreach) on a certain condition, after that, it transfers the control to the beginning of the loop. Basically, it skips its given statements and continues with the next iteration of the loop. Or in o
    2 min read
  • C# Arrays
    An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
    8 min read
  • Your First C Program
    Like in most of the programming languages, program to write the text "Hello, World!" is treated as the first program to learn in C. This step-by-step guide shows you how to create and run your first C program. Table of Content Setting Up Your EnvironmentCreating a Source Code FileNavigating to the S
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences