Difference between For and Foreach Loop in C#

This is very basic question asked in many interviews: 

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. 
 
There is need to specify the loop bounds (minimum or maximum). Following is a code example of a simple for loop that starts 0 till <= 5. 
  1. int j = 0;  
  2. for (int i = 1; i <= 5; i++)  
  3. {  
  4.    j = j + i ;  
  5. }  
The foreach statement repeats a group of embedded statements for each element in an array or an object collection. You do not need to specify the loop bounds minimum or maximum. The following code loops through all items of an array.
  1. int j = 0;  
  2. int[] myArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };  
  3. foreach (int i in myArr )  
  4. {  
  5.    j = j + i ;  
  6. }  
foreach: Treats everything as a collection and reduces the performance. foreach creates an instance of an enumerator (returned from GetEnumerator()) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.
  • Using for loop we can iterate a collection in both direction, that is from index 0 to 9 and from 9 to 0. But using for-each loop, the iteration is possible in forward direction only.
  • In variable declaration, foreach has five variable declarations (three Int32 integers and two arrays of Int32) while for has only three (two Int32 integers and one Int32 array).
  • When it goes to loop through, foreach copies the current array to a new one for the operation. While for doesn't care of that part. 
Interviewer asked me 2 scenario based question in one interview:

    1. for (int i = 1; i <= 5; i++)  
    2. {  
    3.    i = i + i;  
    4. }  
    The above code will work?

    Yes this will work.

    1. int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };  
    2. foreach (int i in tempArr)  
    3. {  
    4.    i = i + 1;  
    5. }  
    Above code will work?

This code will not compile. I have pasted screenshot of error.

foreach

 
Next Recommended Reading for and foreach loop in C#