I have an issue while using my ICloneable class when it comes to cloning lists:
class MetroBoards : ICloneable
{
public int Iteration;
public List<int[]> MetroPieces = new List<int[]>();
public List<char> MetroPiecesDefinition = new List<char>();
public object Clone()
{
return this.MemberwiseClone();
}
}
While trying to update the list in the clone made both this way:
MetroBoards NewBoard = new MetroBoards();
NewBoard = (MetroBoards)ChosenBoard.Clone();
NewBoard.MetroPieces[MoveOne] = Coordinates;
And this way:
MetroBoards (MetroBoards)ChosenBoard.Clone();
NewBoard.MetroPieces[MoveOne] = Coordinates;
Where MoveOne is an integer, and Cordinates are int[]. When I update the List in my clone it updates both the clone and the base.
As far as I have understood, the "MemberwiseClone" should provide me with a deep copy which should create a new object with copies of its properties, which shouldn't be associated with the new object.
EDIT
Thanks to comments I have re-read the documentation and modified the cloning process as:
class MetroBoards : ICloneable
{
public int Iteration;
public List<int[]> MetroPieces = new List<int[]>();
public List<char> MetroPiecesDefinition = new List<char>();
public object Clone()
{
MetroBoards ThisBoard = (MetroBoards)this.MemberwiseClone();
ThisBoard.MetroPieces = new List<int[]>();
foreach (int[] Piece in this.MetroPieces)
{
int[] temp = new int[2];
temp[0] = Piece[0];
temp[1] = Piece[1];
ThisBoard.MetroPieces.Add(temp);
}
return ThisBoard;
}
}
Thank you for making me understand my mistake.