For Vs Foreach In C#

In this article, I will discuss the for and the foreach loop in C# language, their use cases, and when to use which for performance reasons.

Let's start with C# for loop.

for loop in C#

The for loop iterates through items until a certain condition is true. You give an initial statement, a condition for which the loop is to be iterated until it gets false, and a statement that will be executed after every successful block execution.

A normal c# for loop looks like this.

int length = 100;  
for (int index = 1; index < length; index++)  
{  
 //Your code will be here  
 //This is how a programmer makes century.....#ilovecricket  
}

A for loop on a list is like this that goes through a collection and reads each item of the collection. 

List<JCEmployee> JCEmployees = GetJCEmployeesList();  
for (int index = 0; index < JCEmployees.Count; index++)  
{  
    Console.WriteLine(JCEmployees[index].Age);  
} 

Note here that you can directly access the list item by its index.

If you're new to collections, here is a tutorial: Collections in C# 

foreach loop in C#

C# foreach loop is used to iterate through items in collections (Lists, Arrays etc.). When you have a list of items, instead of using a for loop and iterate over the list using its index, you can directly access each element in the list using a foreach loop.

A normal foreach loop looks like this.

List<JCEmployee> JCEmployees = GetJCEmployeesList();  
foreach(JCEmployee Employee in JCEmployees)  
{  
    Console.WriteLine(item.Age);              
}

Note here that a foreach loop creates a copy of the collection on which you are iterating the loop. This means, if you want to perform an assignment operation on the collection item, you cannot directly perform on that item.

To understand that, look at the following example.

For Vs Foreach In C#

Why did that error occur here?

As I said, a foreach loop creates a copy of a collection, so in this loop, the ‘item’ is not referencing to the array elements; it’s just a temporary variable and you cannot assign a value to it.

Also, when it comes to performance, then ‘foreach’ takes much time as compared to the ‘for’ loop because internally, it uses extra memory space, as well as, it uses GetEnumarator() and Next() methods of IEnumerables.

So, the long story short is that when you want your code to be readable and clean, you can use a Foreach loop but whenever you want the performance, you should use a For loop instead.

More?

Here is a detailed article and code samples on the foreach loop - The foreach in C#


Similar Articles