C# Beginner wrote:
Hi there,
This question might be silly to you, but anyway...
How can I move a control at runtime? Object.Location.X = 48; doesn't seem to
work. Do
I really need the code "Object.Location = new
System.Drawing.Point(48,...)???
Funny, we were just talking about this in the "Struct vs Class"
discussion. :-)
The answer is that yes, you have to say:
myControl.Location = new Point(48, myControl.Location.Y);
The reasons are subtle, but perfectly logical.
Remember that Point is a value type. That is, it acts like an integer
or a double. Whenever you assign a Point, you assign a copy. Whenever
you pass it to a method as an argument, you pass a copy. Most
importantly in this case, whenever you return it from a method as a
result, you return a copy. Points are _not_ reference objects like most
things in C# / .NET: you can't fiddle with a Point and expect that
other points change their values as a result.
So, look back at the original code:
myControl.Location.X = 48;
Seems harmless enough, but think about what's really going on here.
Location is a property. So, under the covers, what's really happening
is that you're calling a function called Location_get() to get the
Point value that represents the location of the control. So, you call
the function to get the location Point value, which returns *a copy of*
the value, on the stack. You then modify that copy to set it's X
coordinate to 48. The value then... is thrown away, because it was
never copied into a variable anywhere. In effect, you're doing this:
Point p = myControl.Location;
p.X = 48;
which, of course, doesn't modify anything about myControl.
So, since Location is a property, and any attempt to get its value
results in a copy of the value, not the original value, the only way to
give it a new value is to assign it wholesale:
myControl.Location = new Point(...);