Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is foreach purely “syntactic sugar”?

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?

like image 221
Cui Pengfei 崔鹏飞 Avatar asked Apr 28 '11 09:04

Cui Pengfei 崔鹏飞


People also ask

Is foreach syntactic sugar?

forEach() method is syntactic sugar on top of a for loop.

What is an example of syntactic sugar?

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.

What is the syntax of foreach statement?

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 {}.

Is a for loop syntactic sugar?

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.


2 Answers

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.

like image 129
Jon Skeet Avatar answered Oct 04 '22 15:10

Jon Skeet


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.

like image 44
Daniel Rose Avatar answered Oct 04 '22 15:10

Daniel Rose