pkolodziej
pkolodziej

Reputation: 1367

List<Rectangle> - behaves like there is a boxing

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);
}

Upvotes: 2

Views: 5368

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1064114

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.

Upvotes: 8

Andy
Andy

Reputation: 30418

Because Rectangle is a value type, and calling rects[1] makes a copy of the Rectangle instance at index 1. That's just the way that value types work in .NET, really.

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422252

Yes, the value of the Rectangle will be copied to your local variable if you do that.

It's not called boxing. It's just normal copying, since Rectangle is a value type.

Upvotes: 1

Related Questions