Having an issue with the "this" modifier...
Posted
by user344246
on Stack Overflow
See other posts from Stack Overflow
or by user344246
Published on 2010-05-18T16:41:04Z
Indexed on
2010/05/18
16:50 UTC
Read the original article
Hit count: 130
I have this method in City class. It should create a new city based on the object which the method is applied to:
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 Point class is ment to change the CityCenter location. 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 are both changed. I think that "this" modifier works on the existing object too...
How can I take advantage of the Move method without causing this behavior? Note: this is a closed API, so I can only add private methods to the project.
© Stack Overflow or respective owner