C# Foreach: What it is, How it works, Syntax and Example Code

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.

Prerequisites

The C# Foreach loop is a powerful tool for iterating through collections, such as arrays or lists. However, before you can start using the Foreach loop in your code, there are specific prerequisites that you need to consider. 

  • A programmer should have a collection to iterate over. These collections can be an array, list, or any other type of collection that implements the IEnumerable interface. 
  • And then, the programmer needs a variable to store the current item in the loop. This variable should be the same type as the items in the collection. 

Another essential prerequisite for using the Foreach loop is understanding how it works. Unlike traditional loops, the foreach loop does not require an index or a counter variable. Instead, it automatically iterates over each item in the collection, one at a time. This speciality makes it easier to write clean, readable code. Still, it also means that you must be careful when modifying the collection or the items within it, as this can cause unexpected behavior.

In addition to these prerequisites, it's also essential to understand some of the limitations of the foreach loop. For example, it cannot be used to iterate over a collection in reverse order, and it does not provide access to the current item's index. However, for most common use cases, the Foreach loop is an efficient and effective way to iterate over collections in C#. 

By understanding these prerequisites and limitations, you can use the Foreach loop to its full potential and write more efficient, readable code.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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. 

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.

Traversing an Array of Gender Using a Foreach Loop

Traversing an array of gender using a foreach loop is a common practice in programming. This method is beneficial when dealing with arrays that contain a list of genders. The foreach loop is used to iterate over each element in the array and perform a specific action, such as displaying it on the screen or storing it in a variable. 

Traversing an array of gender using a foreach loop involves declaring a variable to hold each element in the array and then using the foreach loop to iterate over the array. As each element is encountered, it is stored in the variable, and the loop continues to iterate until all elements in the array have been processed. This method is widely used in programming and is an essential skill for any developer who works with arrays.

Foreach Loop With List (Collection)

A foreach loop is a standard loop structure used in programming that allows you to iterate through the elements of a collection. For example, when working with lists in C#, a foreach loop can be handy. A list is a collection type that allows you to store and manipulate related items. Using a foreach loop with a list lets you quickly access and work with each item without worrying about the underlying implementation details.

The foreach loop is handy when you need to operate on each item in a collection.

In C#, for example, you can use a foreach loop to iterate over a List<T> collection. 

Here is an example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

foreach (int number in numbers)

{

    Console.WriteLine(number);

}

In this example, we have a List<int> called numbers that contain five integers. 

  • We then use a foreach loop to iterate over each number list item. 
  • Inside the loop, we use the Console.WriteLine method to give output the current number to the Console. 
  • And the loop will continue until all items in the collection have been processed.

To use a foreach loop with a list in C#, you need to declare the loop variable, which is typically the same type as the items on the list. Then, you can use the loop variable to access each item in the list, one at a time. This approach is often much more straightforward and concise than a traditional for loop, requiring you to manage the loop counter and index variables manually.

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.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Implement IEnumerable Interface

The IEnumerable interface in C# allows developers to create custom collections that can be iterated using a foreach loop. To implement the IEnumerable interface, a class must define a method called GetEnumerator(), which returns an object. And the object provides methods for iterating through the collection, including MoveNext(), which moves the iterator to the next element, and Current, which returns the current element.

Implementing the IEnumerable interface can be helpful in various scenarios, such as when working with complex data structures or performing custom filtering or sorting of data. It can also be used to create custom iterators that allow for lazy data loading, improving performance in certain situations.

To use a custom collection that implements the IEnumerable interface, create an instance of the collection and use it in a foreach loop. The loop will automatically call the GetEnumerator() method and iterate through the collection using the methods provided by the IEnumerator object. 

By implementing the IEnumerable interface, developers can create powerful and flexible collections that can be easily integrated into their applications.

C# Foreach Loop in Dictionary

One of the critical features of C# is the foreach loop, which allows developers to iterate through a collection of objects and perform operations on them. For example, in the case of a dictionary, the foreach loop can be used to iterate through the key-value pairs in the collection. 

This dictionary is implemented by using the KeyValuePair data type, representing a pair of objects, one for the key and one for the value. The foreach loop is an efficient way to process extensive data collections and can be used in various scenarios, such as data processing, data analysis, and report generation. 

A foreach loop in C# can iterate over the key-value pairs in a dictionary. You can use the KeyValuePair<TKey, TValue> structure to access each key-value pair in the dictionary. 

Here's an example:

Dictionary<string, int> ages = new Dictionary<string, int>

{

    { "Alex", 25 },

    { "Hannah", 20 },

    { "Maeve", 21 }

};

foreach (KeyValuePair<string, int> pair in ages)

{

    Console.WriteLine("{0} is {1} years old.", pair.Key, pair.Value);

}

In this example, we create a Dictionary<string, int> called ages, which contains the ages of three people. We then use a foreach loop to iterate over each key-value pair in the ages dictionary. Inside the loop, we use the pair. Key and pair.Value properties to access the key and value of the current pair, respectively.

Foreach Loop Skips to the Next Item

A foreach loop is a famous structure in programming languages like PHP, Java, and C#. It is used to iterate through an array or collection of elements and perform specific actions on each element. Sometimes, while iterating through a loop, we may want to skip certain elements and move on to the next one. 

We can use the "continue" statement within the loop in such cases. The continue statement tells the loop to skip the current iteration and move on to the next one. This is particularly useful when filtering out certain elements from our loop. In addition, we can use conditional statements within the loop to determine which elements to skip and which to process. 

Here's an example:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int number in numbers)

{

    if (number == 3)

    {

        continue;

    }

    Console.WriteLine(number);

}

And the output code will be, 

1

2

4

5

Foreach Loop: Break

The foreach loop in programming is a popular construct that iterates over a collection of data elements. It is a simple and efficient way to access each collection component and perform some operations. However, there may be situations where we need to break out of the loop prematurely. This is where the break statement comes in handy. 

When placed inside a foreach loop, the break statement immediately exits the loop and continues with the following line of code outside the loop. It is a valuable tool in controlling the program flow and can be used to optimize performance by avoiding unnecessary iterations.

Here's an example:

int[] numbers = { 6, 7, 8, 9, 1 };

foreach (int number in numbers)

{

    if (number == 8)

    {

        break;

    }

    Console.WriteLine(number);

}

And the output will be,

6

7

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

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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.

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 Developer - MERN Stack to master both backend and frontend with other tools like SpringBoot, AngularMVC, JSPs, and Hibernate to start your career as a full-stack developer.

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.