Sam
Sam

Reputation: 2347

Modifying value of object within foreach loop

I defined a list of rectangles called enemies, and I'm trying to move through the rectangles in the list and decrement their X value, but I am getting an error "cannot modify 'i' because it is a foreach iteration variable." I'm wondering what is wrong with this and if there is a correct way of going about it.

        foreach (Rectangle i in enemies)
        {

            i.X --:

        }

Upvotes: 2

Views: 810

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 659984

Value types are copied by value; that's why they're called "value types". When you do this, you are making a copy of the rectangle and then mutating the copy. Now, it just so happens that the foreach loop makes an immutable copy of the value and tells you that you cannot change it, which is good, because it just caught your bug. Had you been making that change to a mutable copy you might not have found the bug for a long time.

Your Enemy type should probably be a reference type, not a value type. Have the enemy contain a rectangle, not be a rectangle. You can then mutate the rectangle in the reference to the enemy.

Upvotes: 8

Related Questions