2

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 --:

        }
4
  • 3
    It sounds like you're using an evil mutable struct. Don't. Commented Feb 27, 2012 at 19:45
  • 4
    What do you have against Rectangles that make them enemies? :/ More to the point, is this the System.Drawing.Rectangle struct, is it a custom struct of yours, or _____? Commented Feb 27, 2012 at 19:47
  • I figured you're referring to an XNA Rectange (which is a Struct) as opposed to the WPF Rectangle class, so I added xna as a tag. Commented Feb 27, 2012 at 19:47
  • @AnthonyPegram: "What do you have against Rectangles that make them enemies?" -- That made me laugh a bit. Commented Feb 27, 2012 at 19:52

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

While I agree that Enemy should possibly a reference type, there is one small caveat when it comes to XNA: If you want to run on the Xbox 360, the garbage collector is a big issue, which is why mutable structs are somewhat more common there. Trying to make a game with many enemies (e.g., Geometry Wars) could be a performance challenge (although I'd assume Object Pooling makes much more sense than mutable structs).
@MichaelStum: Keep in mind that I took a guess that the original poster was using XNA, so I added that tag. It makes sense because in XNA Rectangle is a struct, but there is still a tiny chance the OP was using another struct Rectangle? Maybe...
Nope, you were correct in assuming it was XNA :) thanks for the help all, I just recently started using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.