Cannot modify members of ‘item’ because it is a ‘foreach iteration variable’

 I had a compile time issue with using my custom list. The code simply looks like the following:

 

foreach (ItemType item in listOfItems)

    item.CustomAccessor = "value";

 

And compiler complains with error:

            Cannot modify members of ‘item’ because it is a ‘foreach iteration variable’

 

This is because the ItemType is defined as a  struct and not as a class. Doing so the iteration of foreach will result to some copies of the heap that are not reflecting the real objects. The question that has often been asked is why did you define your ItemType as struct and not as a class…. which I will answer it in other discussion.

  

Author: Pouya Panahy

Microsoft certified DevOps engineer with passion in analysing, designing and implementing solutions for Azure Cloud with hands-on experience in security and quality assurence.

Leave a Reply