In modern programming, loops play a fundamental role in optimizing and simplifying the coding process. Loops are conditional iterative instructions that execute a block of statements until the test condition stays true. They carry out a repeated sequence without the need to write codes repeatedly. The most common examples of loops in programming include the while loop and the for a loop.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

Introduction to foreach in C#

The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.

How Does It Work?

The foreach loop in C# uses the ‘in’ keyword to iterate over the iterable item.

The in keyword selects an item from the collection for the iteration and stores it in a variable called the loop variable, and the value of the loop variable changes in every iteration. For example, the first iteration process will have the first item of the collection stored; the second iteration will have the second item of the collection stored, and so on.

The number of iterations of the C# foreach loop equals the total items in the collection. Here’s a flowchart showing the working of the C# foreach loop.

C_Sharp_foreach_1.

A few key points to note:

  1. All the statements of the foreach loop must be enclosed within curly braces { }.
  2. The Foreach loop uses the loop variable instead of the indexed element to perform the iteration.
  3. The C# foreach loop only requires the declaration of a variable with the same data type as the base type of the collection or array instead of a loop counter variable. 

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

The Syntax of C# foreach

Here is the syntax of C# foreach loop.

foreach (datatype variable name in iterable-item)

{

    // body of the loop

}

Sample Code to Understand the Working of C# foreach

Here’s a basic program to understand the working of the foreach loop. In this program, we’ve created an array with 6 elements from 0-5, and the goal is to display each element using the foreach loop on the output screen.

// C# foreach loop program to illustrate the working of the loop

using System;

class loopworks 

{

   static public void Main()

    {  

        Console.WriteLine("Print array:");   //displays text on output window

        int[] arr_array = new int[] { 0, 1, 2, 3, 4, 5, };    // array creation       

         // foreach loop begins and runs till last item

        foreach(int i in arr_array)

        {

            Console.WriteLine(i);

        }

    }

} // end of code

Output

0

1

2

3

4

5

C_Sharp_foreach_2.

For understanding the code better, here’s an equivalent for loop code for the same goal.

for(int i = 0; i < arr_array.Length; i++)

{

    Console.WriteLine(arr_array[i]);

}

Replacing this code with the foreach loop code in the above program will give the same output.

Example Codes of C# Foreach

Use foreach to Find a Char in a String

Foreach can also be used to check whether a certain character is present in a given string.

using System;

class loopworkseg1

{

   static public void Main()

    {

        //reading the string

        string s = "Zahwah Jameel";          

        //converting string to array with characters as items

        char[] chArray = s.ToCharArray();

        foreach (char ch in chArray)  

        {  

            if (ch.ToString() != " ")  

            Console.WriteLine(ch);  

        }

    }

}

Output:

C_Sharp_foreach_3.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Foreach in Collection

The C# foreach loop can be implemented to read the number of occurrences of a certain number or character in the collection. Here’s the sample code:  

using System;

class loopworkseg2

{

   static public void Main()

    {

        // Find number of occurrences of a char in a string  

        string str = "education is free";  

        char[] chars = str.ToCharArray();  

        int ecount = 0;  

        // Loop through chars and find all 'n' and count them  

        foreach (char ch in chars)  

        {  

            if (ch == 'e')  

            ecount++;  

        }  

        Console.WriteLine($"Total e found {ecount}");

    }

}

Output

C_Sharp_foreach_4.

Foreach in Array

This sample code reads all the strings in an array and displays them through the C# foreach loop.

using System;

class loopworkseg3 

{

   static public void Main()

    {

        string[] dessertList = new string[]   // Array with all the desserts

        { "Apple Pie", "Coconut Cookie", "Choco Lava Cake", "Icecream", "Banana Pudding" };  

        // Loop through array and read and display all desserts  

        foreach (string dessert in dessertList )  

        {  

            Console.WriteLine(dessert);  

        }

    }

}

Output

C_Sharp_foreach_5

The Limitations of foreach

Although the foreach loop has high readability and requires a low learning curve, especially if you already code in other languages, it is not without limitations.

  1. They don’t keep track of the index of the item.
  2. They cannot iterate backwards. The loop can only go forward in one step. 
  3. If you wish to modify the array, the foreach loop isn’t the most suitable option.
  4. The foreach loop cannot execute two-decision statements at once.

For vs Foreach: What Are the Differences?

Although both for and foreach are loop statements, here are a few key differences listed in the table:

The C# For Loop

THE C# Foreach Loop

Executes a statement or a block of statements until the given condition is false.

It executes a statement or a block of statements for each element present in the array.

Works on maximum and minimum limits

Does not require defining limits.

We iterate the array in both forward and backward directions,

Only forward.

for loop only has three variable declarations.

foreach loop has five variable declarations.

Uses loop counter variable.

Only needs a variable declared with the same data type as the base of the collection.

No creation of array copies.

Creates an array copy for the operation.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

The C# foreach loop is a basic looping concept with extensive use in programming. Although programmers require a minor learning curve, implementing the concept requires in-depth learning and study materials and resources.

If you’re enthusiastic about learning C# for developing desktop and web applications, Simplilearn offers an extensive full-stack web development certification course to master both backend and frontend with other tools like SpringBoot, AngularMVC, JSPs, and Hibernate to start your career as a full-stack developer.

You can also look up various free online skill-up courses offered by Simplilearn in several domains, from data science and business analytics to software development, AI, and machine learning.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors