18
In a video tutorial the instructor stated not to fall for the nonsense of thinking that the foreach is a loop, and it was vehement that he was an iterator.
There are cases where we can go through the items of an array using foreach as a "compact for version".
That is, when we use foreach for arrays or matrices, in the background we are using it as a compact version of loop for. When we use it to iterate collections, it is in fact a TRUE iterator because "access" the methods of the Ienumerator
Is the statement correct? Can anyone add anything about it?
Follow example code:
//foreach com Arrays
int[] array = new int[]{1, 2, 3, 4, 5, 6};
foreach (int item in array)
{
Console.WriteLine(item);
}
However, the C# compiler generates C# code equivalent to the generated CIL:
//Código C# equivalente ao CIL gerado
int[] tempArray;
int[] array = new int[]{1, 2, 3, 4, 5, 6};
tempArray = array;
for (int counter = 0; (counter < tempArray.Length); counter++) {
int item = tempArray[counter];
Console.WriteLine(item);
}
The code above was taken from the book: Essential C-6.0, 5th Edition [ Author Mark Michaelis ] page 582
This excerpt from the book "Listing 14.6 demonstrates a simple foreach loop iterating over an array ..." is enlightening.
– ramaral