The compiler compiles a foreach
loop into something like a for
loop when the foreach
is used with an array. And the compiler compile
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.