We have already seen, in previous lessons, how to iterate through an array/collection with the for() looping statement. However, there is another iteration statement available to you that can complete this task called foreach(). This looping statement can be seen as a simplified for() loop, using a fixed single-step increment and automatically terminating at the last indexed item within the array/collection.
You can execute the code-snippet for the foreach() loop by typing in “foreach()” and hitting the tab key twice. The foreach() is structured as follows:
The data type for the item in the array/collection.
The temporary identifier, local only to the loop, for referencing each item in the iteration.
The ‘in’ keyword, denoting relationship between the item and the array/collection it is in.
The identifier for the array/collection you want to iterate through.
In the previous lesson, we used a for() loop to iterate through the List<Car>. Let’s perform the equivalent task but with using a foreach() loop instead:
This is, essentially, a more intuitive way of representing a for() loop with a single-step incrementing counter:
Notice how the foreach() loop doesn’t even use an indexer because it’s already implied that we’re moving up one index for each iteration. You can certainly include an indexer, but it would be redundant:
Also, notice how the foreach() stores each iterated item into a temporary local variable, which you can use to access the properties/methods available to that item. It’s important to remember that the value this temporary variable stores gets re-written with each successive iteration:
Notice how the syntax in the foreach() loop is inherently readable and expresses exactly what is happening, which is essentially: “for each item in the collection, do this…”
Lesson 50 - Looping with the foreach Iteration Statement