0

I have a class with a Rectangle property as following:

public class Test {
    public Rectangle Rect { set; get; }
}

Outside of the class, I am trying to decrease the height of the Rect by 20, but I get an error that is not allowed as it's not a variable.

Then I used TestObj.Rect.Inflate(0,-20);, I had no error but it has no effect on the height of Rect when I run the program.

I can understand for the same reason as above, it shouldn't work, but why I don't receive any error? Is there a general rule for it?

Then what is the best way to decrease the height of Rect?

Ahmad
  • 8,811
  • 11
  • 76
  • 141

3 Answers3

3

Rectangle is a value type, so it will be copied by value. When calling Inflate on Rect property you're modifying the copy. Not the actual rectangle.

If Rect were a field instead of a property it would have worked because accessing a field doesn't need to copy the value.

I mean the following will work

public class Test
{
    public Rectangle Rect;
}

Given that Rect is a property, you need to reassign the computed value to make it work.

Refer Mutable value types are Evil

Community
  • 1
  • 1
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
1

The problem with Inflate is it also affects the Y coordinate, assuming you purely only want to resize the height then you can just re-create the Rectangle with the adjusted height

new Rectangle(Test.Rect.Location, new Size(Test.Rect.Width, Test.Rect.Height - 20));
James
  • 80,725
  • 18
  • 167
  • 237
1

Rectangle is a value type. Inflate method returns new instance of Rectangle but not correct current.

Yuri Dorokhov
  • 716
  • 5
  • 24