Tutorial :Expose class attributes with accessor


I don't know the correct technical terms to describe my question, so I'll give an example:

    private Point _PrivateVect = new Point();      public Point Publicvect      {          get          {              return _PrivateVect;          }          set          {              _PrivateVect = value;          }      }  

The problem is that if I wanted to access Publicvect.X I get the error Cannot modify the return value of 'Publicvect' because it is not a variable. Is there a way around this? Or do I just need to do Publicvect = new Point(NewX, Publicvect.Y); forever?


Yet another reason that mutable structs are evil. One workaround is to expose the dimensions as accessors for convenience:

public Point PublicX {      get {return _PrivateVect.X;}      set {_PrivateVect.X = value;}  }  public Point PublicY {      get {return _PrivateVect.Y;}      set {_PrivateVect.Y = value;}  }  

But other that this; yes you would need to do the new Point(x,y) each time, since Point is a struct. When you access it via a property you get a copy of it, so if you mutate the copy and then discard the copy, you simply lose the change.


The problem you have here is that the Point type is a Value Type. So when you manipulate Pointvect.X you are really manipulating a temporary copy of the value type, which of course has no effect on the original instance.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »