I have an array of structs. Does foreach operator make a copy of each element when iterating thru an array? As far as I understand foreach is just syntactic sugar under the hood converted to for. So it appears the answer is no but I’d love to have some confirmation.
PS: it appears someone should have already asked that but I can’t easily find anything. So please vote as a dup with provided reference.
Yes, copies of the value type instances will be made. When iterating over an array,
foreachwill indeed use array accesses instead of using an enumerator, but the value in each array slot is still copied.This code:
Generates the following IL for the
Main()method:Note the instructions IL_0013 through IL_001d. The entire value at each array slot is pushed onto the stack and stored in the local V_3 (the
xiteration variable).