C# forEach loop | When to Use, How it Works

In C#, the “foreach” loop is used to iterate over elements in a collection. The Collection types such as Array, ArrayList, List, Hashtable, Dictionary, etc.  It executes for each element present in the Array. In this article, we will learn C# foreach loop | When to Use it, and How it Works.

Syntax of ‘foreach’ loop

foreach(var items in collection)
{
    // set of statements
}

“collection” – represents the collection or array, to iterate.
“items” – is a variable that will hold each element of the collection during each iteration.

How does it work?

Here’s a Flowchart showing the working of the C sharp foreach loop.

C# forEach loop

A few key points while working on foreach loop

  • It is necessary to enclose all the statements of the foreach loop in curly braces {}.
  • The Foreach loop uses the loop variable rather than using an indexed element to perform the iteration.
  • In C#  foreach loop, instead of declaring and initializing a loop counter variable only requires the declaration of a variable with the same data type as the base type of the collection

Here the following example demonstrates, the iteration of an array using a foreach loop

string[] departments = { "Computer Science", "Mechanical", "Electronics", "Civil", "Electrical" };

foreach(var items in departments)
{
     Console.WriteLine(items.ToString());
}

Output:

Computer Science
Mechanical
Electronics
Civil
Electrical

another example demonstrates, ‘foreach‘ loop on a List Collection.

List<string> listforeach = new List<string>() { "Computer Science", "Mechanical", "Electronics", "Civil", "Electrical" };

foreach(var item in listforeach)
{
  Console.WriteLine($"{item}");
}

listforeach.ForEach(item=>Console.WriteLine(item));

Output:

Computer Science
Mechanical
Electronics
Civil
Electrical
 // ForEach Extension Method
Computer Science
Mechanical
Electronics
Civil
Electrical

The following example demonstrates the foreach loop on a dictionary collection.


var ListofDept = new Dictionary<string, string>()
{
    {"SC" ,"Computer Sceince" },
    {"Mech" ,"Mechanical Engineering" },
    {"ECE" ,"Electronics and Communication Engineering" },
    {"CE" ,"Civil Engineering" },
};
foreach(var item in ListofDept)
{
    Console.WriteLine($"Department {item.Key}  , {item.Value}");
}

Output:

Department -- SC  , Computer Sceince
Department -- Mech  , Mechanical Engineering
Department -- ECE  , Electronics and Communication Engineering
Department -- CE  , Civil Engineering

When to Use ‘foreach’ Loop:

Following scenarios use the ‘foreach’ Loop.

  • Iterating collection – like iterate through a collection such as an array, List, Dictionary, or any object that implements ‘IEnumerable’, ‘IEnumerable<T>’, or ‘IEnumerator’.
  • Simplicity – using foreach loop to maintain cleaner and more concise code.
  • Type Safety – it automatically determines the type of the loop variable based on the collection type.
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments