Reputation: 13
Why is this code below legal
Point point = new Point();
point.X = 6;
point.Y = 5;
but this generates error?
myButton.Location.X = 6;
myButton.Location.Y = 5;
I know that structs are value type, we get copy, so we cannot modify Location.X
indirectly and we have to assign to myButton.Location
a whole new struct as new Point(6,5)
, but why does point.X = 6
work?
I don't get the difference.
Upvotes: 1
Views: 203
Reputation: 460108
From MSDN: How to: Position Controls on Windows Forms
Use the
Location
property to set a control's X and Y positions simultaneously. To set a position individually, use the control's Left (X) or Top (Y) subproperty. Do not try to implicitly set the X and Y coordinates of the Point structure that represents the button's location, because this structure contains a copy of the button's coordinates.
Because the Point class is a value type, it is returned by value, meaning accessing the property returns a copy of the upper-left point of the control. So, adjusting the X or Y properties of the Point returned from this property will not affect the Left, Right, Top, or Bottom property values of the control. To adjust these properties set each property value individually, or set the Location property with a new Point.
Upvotes: 1
Reputation: 33381
Because when you say myButton.Location
Location
already is copy, and you have not any reference to it. And change of any object and to loss it doesn't have meaning.
Upvotes: 0
Reputation: 1500504
but why point.X = 6 works?
Because point
is a variable. You're just modifying one part of the value of the variable. That's allowed and useful (although I'd personally steer away from using mutable value types wherever possible).
So for example, you can write:
Point point = myButton.Location;
point.X = 6;
myButton.Location = point;
... and that will effectively just change the value of X
for myButton.Location
.
Changing part of a value which is copied and then lost is not useful.
Upvotes: 1