Question:
Hello! This question is about optimality.
Which of the two, when programmatically creating a control in WinForms, is it better to set the coordinates?
1) element.Location = new Point(x, y);
2) element.Location.X = x; element.Location.Y = y;
Is it advisable to initialize a Point
instance (although it takes less space and looks prettier)?
Answer:
2) element.Location.X = x; element.Location.Y = y;
This option is not working. In Location
, you can write Point
as a whole, and access to Location.X
and Location.Y
is read-only, because Location
is a property and not a variable or field, which the studio warns about even before compilation.
The reason is quite simple – structures in .NET are value types, therefore, when accessing a property, it provides a copy of the Point
value and it makes no sense to make changes to it.