There is such a situation

struct Point { int x; int y; public void SetX(int a){ ... } public void SetY(int a){ ... } } class A { Point cord = new Point(); public Point Cord { get { return cord; } } public void MethodA(int a) { cord.SetX(a); //здесь все ок } } class B { A myObj = new A(); public Point Cord { get { return cord; } } public void MethodB(int a) { myObj.Cord.SetX(a); //а здесь не присваивает значение } } 

In class A, the method works correctly, but in class B it does not (comes in a method, assigns something to something, but in the myObj object and in its cord field of type Point is not) I wonder why this value is assigned and why it works with classes but there is no structure.

  • This will not compile. You are asking members whose access level is implicitly set to private . - Vadim Ovchinnikov
  • @VadimOvchinnikov, most likely there is a typo and a property call goes myObj.Cord.SetX(a); - Grundy
  • @VadimOvchinnikov, yes, it was sealed up - Mikhail Znak

1 answer 1

Because the structure is ValueType and is copied completely.

As a result of the call

 get { return cord; } 

There will be a new structure object in which you SetX method.

  • why is the new one, I have a cord field, and is it just its property? - Mikhail Znak
  • one
    @MikhailZnak, because such behavior of structures: when they are passed as parameters or returned as the result of a method - a full copy of the object is transmitted and returned. Except for the ref and out parameters - Grundy
  • one
    @MikhailZnak, use the class instead of the structure, the second option is to add a setter for the field in which you will install a new object - Grundy
  • 2
    This, by the way, is one of the classic examples of why mutable structures are evil. - VladD
  • one
    @MikhailZnak: To correct the code, do this: read a copy of the structure, change it by calling the method, and write back to the original place via setter. - VladD