-
When writing a
forloop that accesses each element of an array once, you will end up writing code like this:for(int i = 0; i < myArray.Length; i++) { <do something with myArray[i]>; } -
In some cases, this code has unnecessary repetition: If you are not using the counter
ifor anything other than an array index, you still need to declare it, increment it, and write the condition withmyArray.Length -
The foreach loop is a shortcut that allows you to get rid of the counter variable and the loop condition. It has this syntax:
foreach(<type> <variableName> in <arrayName>) { <do something with variable> }- The loop will repeat exactly as many times as there are elements in the array
- On each iteration of the loop, the variable will be assigned the next value from the array, in order
- The variable must be the same type as the array
-
For example, this loop accesses each element of
homeworkGradesand computes their sum:int sum = 0; foreach(int grade in homeworkGrades) { sum += grade; }- The variable
gradeis declared with typeintsincehomeworkGradesis an array ofint gradehas a scope limited to the body of the loop, just like the counter variablei- In successive iterations of the loop
gradewill have the valuehomeworkGrades[0], thenhomeworkGrades[1], and so on, throughhomeworkGrades[homeworkGrades.Length - 1]
- The variable
-
A
foreachloop is read-only with respect to the array: The loop’s variable cannot be used to change any elements of the array. This code will result in an error:foreach(int grade in homeworkGrades) { grade = int.Parse(Console.ReadLine()); }