For Vs Foreach In C#

In C#, for vs foreach loop can be confusing. This article explains when to use for vs foreach loop 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

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.

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

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

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

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

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.

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

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#