Memory allocation when using foreach loops in C#

前端 未结 4 487
暖寄归人
暖寄归人 2021-02-03 23:52

I know the basics on how foreach loops work in C# (How do foreach loops work in C#)

I am wondering whether using foreach allocates memory that may cause garbage collecti

4条回答
  •  青春惊慌失措
    2021-02-04 00:31

    Because an enumerator keeps hold of the current item. It's like a cursor compared to databases. If multiple threads would access the same enumerator, you would lose control of the sequence. And you would have to reset it to the first item every time a foreach consults it.

提交回复
热议问题