There is a problem with the "this" modifier

I have this method in my City class. It should create a new city based on the object to which the method is applied:

 public City newCity(string newCityName, int dX, int dY)
    {
        City c=new City(this); //based on a constructor : City(City c){}

        c.CityName=newCityName;
        c.NoOfNeighborhoods=1;
        c.NumOfResidents=0;
        c.CityCenter.Move(dX,dY);

        return c;
    }

      

CityCenter is of type "Point", which has two fields - x, y. the Move method in the Point class is intended to change the location of the CityCenter. It looks like this:

 public void Move(int dX, int dY)
    {
        this.X = x + dX;
        this.Y = y + dY;
    }

      

What happens is that the new object, c, and the existing City object have changed. I think the "this" modifier also works on an existing object ...

How can I use the Move method without causing this behavior? Note: this is a private API, so I can only add private methods to the project.

+2


a source to share


3 answers


I'm assuming Point is a class, so you are passing a reference to the same point instance. You will need to create a new Point instance and assign it to the new City.CityCenter



+1


a source


I suspect it is City c=new City(this);

creating a shallow clone of the current City, which means they both have the same Point object (can only be true if Point is a class and not a struct).



Can you do City c=new City();

this instead?

+4


a source


The problem (almost certainly) is that both cities reference the same object Point

. When you change an object, that change is visible through both references. Parameters:

  • Create a new Point object when cloning a city.
  • Dot the value type (so that an independent copy of the
  • Make Point an immutable type and change Move

    to return a new Point with an appropriate change.

(or some combination of the above ...)

It looks to me like Point should probably be a value type (struct). Please note that structures must always be immutable.

It seems somewhat odd to have an instance method newCity

in the first place - what is the relationship between a new city and an old city? Why don't you just create a completely separate city?

+2


a source







All Articles