Is foreach purely “syntactic sugar”?

前端 未结 5 1409
南旧
南旧 2020-12-06 10:32

The compiler compiles a foreach loop into something like a for loop when the foreach is used with an array. And the compiler compile

5条回答
  •  我在风中等你
    2020-12-06 10:54

    It is not just syntactic sugar as the items in a foreach loop are immutable (unchangeable). The reason for this, as Daniel so kindly pointed out, is that most collections will use an enumerator in a foreach, and it is the enumerator that has the restriction of not letting you update the contents of the list while it is being enumerated.

    i.e.

    Foreach(String s in List)
    {
       s = "f";  //this will throw an error.
    }
    

提交回复
热议问题