"Cannot assign members of variable because it is a foreach iteration variable"

Hello everyone,

So i’ve got an array made of variables, which are actually copies of an struct which I had defined before, one of the properties in this struct (it’s called tileInfo) it’s tileInfo.ID, which stores the ID of every block in my array. I’ve made an script using a foreach loop (in C#) to assign different values to every block (for example, assigning a value to tileInfo.name) according to each block’s ID, it looks like this:

foreach(tileID t in arrayOfTiles){
     if(t.ID == 1){t.name = "Stones";)}

That’s simpler than my code, but it creates the same error. The error i’m getting it’s: Cannot assign members of `t’ because it is a foreach iteration variable

So what it’s telling me, is that I cannot access the properties of my struct in the variable in which i’m running the for loop? Is there any way to fix that? Or would I have to do a normal for bucle to run through all my array?

Thank you very much

Since tileID is a struct (as opposed to a class), it is accessed by-value. Assigning it from A to B will copy the whole struct, including contents.

Assigning a class (which is always by-reference) from A to B on the other hand, will only copy the reference to the actual object, so changing A.member will also change B.member.

Analogon: Vector3 is a struct. So this example code will also not change your original array, and probably produce the same error:

foreach(Vector3 v in myVectorArray)

Instead, since you apparently already have an array, use a regular for-loop:

for(int i=0;i<arrayOfTiles.Length;i++)
     if(arrayOfTiles_.ID == 1){arrayOfTiles*.name = "Stones";)}*_

The other solution would be to make tileID a class, not a struct.

It’s because you are using a struct and t has become a copy of the entry in the array. If you used a class then this would not be a problem. Generally speaking it is better to use classes than structs due to memory fragmentation issues when using variable length data structures in any case - but of course you may have a very good reason for using struct - like packing a smaller representation of your data.

Structs give a number of problems due to their copy behaviour - but again, maybe you are using them because you want to be able to easily copy a value. You can deep copy classes using BinaryFormatter and MemoryStream.