I am new in C#. I am from Java world. So I am confused with the following code:
class A
{
private PointF point;
public A(PointF point)
{
this.point = point;
}
public PointF Position
{
get { return point; }
}
}
I want to change X-coordinate of the position property, so I perform:
A a = new A(new PointF(1,2));
PointF p = a.Position;
p.X = 100;
Console.WriteLine(a.Position.X); // <--- I have 1 here!
I wonder why the output is NOT 100? As I have understand I have received reference on private field with Position property. Am I right?
Can I change property without adding set-property and propagating Position with new PointF object?
No;
PointFis astruct, so it has copy semantics and is not an object; as soon as you’ve obtained it – it is a separate and isolated copy (unless you’re using something likeref/out, which is … more subtle). The struct is actually copied multiple times in your example.By the way, a consequence of this is that it is actually a very bad idea to have mutable structs – so in most cases you should avoid the scenario where you can say:
since that causes more confusion than it helps. In particular the following is completely invalid:
(here the compile is spotting that you are changing a copy of the struct that only exists during the mutation itself, which means your change goes nowhere, and is almost certainly a bug)