The compiler compiles a foreach
loop into something like a for
loop when the foreach
is used with an array. And the compiler compiles a foreach
loop into something like a while
loop when the foreach
is used with an IEnumerable
or IEnumerable<T>
. So does this mean foreach
is purely syntactic sugar
? Or is there anything sophisticated about it?
Does the CLR know about foreach
? Is there anything specifically designed for foreach
in the MSIL code?
forEach() method is syntactic sugar on top of a for loop.
For example, if a syntactic sugar for the unskilled programmer is a command like “make X equal to one” and the skilled programmer shortcut is “X = 1,” both of these could be considered syntactic sugar in their own ways.
The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array. It is necessary to enclose the statements of foreach loop in curly braces {}.
The for...of loop is syntactic sugar the for loop. The for loop creates a loop that executes as long as the condition evaluates to true . It takes in three optional expressions, the initialization, condition, and final expression.
It's purely syntactic sugar in that you could obtain the same behaviour without it, yes. Many other things are the same... for
, while
etc... To misquote Archimedes: "Give me if
and goto
, and I will move the code..."
No, the CLR doesn't have any concept of foreach
.
It is syntactic sugar. However, note that foreach works by calling GetEnumerator(), then MoveNext() until there is no further item returned and then always calls Dispose() on the enumerator it previously obtained. If you want to do it the same way, don't forget that Dispose()!
Also, the CLR does some tricks related to getting the enumerator. See here and here, for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With