We all know that generic List<> does not box value types. Why on the following code snippet the rects[1] is not affected by Inflate method?
If there is no boxing and I want to afect the rect[1] I need to write three lines of code as it is shown – commented. Can someone please explain this?
List<Rectangle> rects = new List<Rectangle>(); for (int i = 0; i < 5; i++) { rects.Add(new Rectangle(1, 1, 1, 1)); } foreach (Rectangle item in rects) { Console.WriteLine(item); } //Rectangle r = rects[1]; //r.Inflate(100, 100); //rects[1] = r; rects[1].Inflate(100, 100); foreach (Rectangle item in rects) { Console.WriteLine(item); }
It isn’t boxing – simply that when you get the rectangle out, you are manipulating a standalone copy of the rectangle.
This is one of the side effect of having mutable value-types (structs). And the reason you shouldn’t write your own mutable structs – it is too easy to lose data.
Since you can’t make the pre-built rectangle immutable, I’m afraid you’re going to have to copy it out; mutate it; and put it back in.