Difference between for loop and foreach statement in C#

 

Code inside "for" loop will execute if the condition satisfied and foreach loop is specially designed for accessing the values of arrays and collections. In the case foreach statement, for each iteration of the loop one value of the array is returned through the loop variable in a sequential order. 

for loop Example: 

for (int i = 1; i <= 10; i++) 

{

         Console.WriteLine(i.ToString());    

}

As shown above, for loop will execute for 10 times because we are comparing the variable i less than or equal to 10.

 

foreach statment Example: 

string[] strArray = new string[]{ "A", "B", "C" };

 

foreach (string str in strArray) 

{ 

       Console.WriteLine(str);   

}

As shown above, foreach statement executes three times because strArray has three elements.

 

Differences between for loop and foreach statement 

In the case of for loop, variable of the loop refers to the index of the array. While in the case of foreach statment, variable refers to values of the array. 

In the case of for loop, variable data type is int always irrespective of data type of the values in array. In the case of foreach statement variable data type is same as data type of values in array. 

"this" can be used for both accessing and assigning values of an array in the case of "for" loop. While in the case of foreach statement "this" can be used only for accessing the values but not for assigning the values.