KamCho KamCho - 1 month ago 12
C# Question

Making an independent List<T>

I want to have two lists of points in my class. One for the originally loaded values and second for modified values. I'm making two separate lists in my class but when I'm trying to change it by change_points method the start_pnts list also change it's values. I have no idea what I'm doing wrong. I'll be thankful for any help with this simple problem.

class Polygon : Shape
{
private List<Point> points = new List<Point>();
private List<Point> start_pnts = new List<Point>();

public override void add_point(Point pnt)
{
start_pnts.Add(pnt);
points.Add(pnt);
}

public override void change_points(double x, double y)
{
for (int i = 0; i < points.Count; i++)
{
points[i].x = start_pnts[i].x + x;
points[i].y = start_pnts[i].y + y;
}
}
}

Answer

Actually you're saving the same reference, so it's obvious that you will get the changes reflected to the 2 lists. I will suggest to use a Point struct instead of class, an thus you will work with copy values instead of references or as suggested implement ICloneable interface to implement you copy logic there.