-1

I have a class called Board. It has multiple columns and you can add Stones to a column by Calling AddStoneToColumn(column c). The method shouldnt modify the objet itselft but only create a new Board Object with the added stone but somehow it keeps changing itself too.

Heres my relevant Code:

public Board AddStoneToColumn(int column)
{
    Board resultBoard = new Board(this);
    Boolean isPlaced = false;
    for (int i = 0; i < height; i++)
    {
        if (resultBoard.GetStone(column, i) == StoneEnum.EMPTY)
        {
            resultBoard.SetExactCoords(column, i, turn);
            isPlaced = true;
            break;
        }
    }

    if (!isPlaced)
    {
        throw new InvalidOperationException("Spalte voll");
    }

    if (turn == StoneEnum.BLUE)
        resultBoard.turn = StoneEnum.RED;
    if (turn == StoneEnum.RED)
        resultBoard.turn = StoneEnum.BLUE;
    return resultBoard;
}

private void SetExactCoords(int x, int y, StoneEnum stone)
{
    if (stone == StoneEnum.EMPTY)
        throw new NotSupportedException("Empty stone ??");
    this.stones[x, y] = stone;
}

public Board(Board board)
{
    this.stones = board.stones;
    this.turn = board.turn;
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • We don´t know what `Board(this)` does, but I assume it´s a copy-constructor that just creates a shallow copy of `this`. What I assume is you want a **deep** copy instead. – MakePeaceGreatAgain Feb 22 '19 at 13:50
  • Board(this) is the constructor at the end of my code. But Daniel already answered my question good. – J. Krueger Feb 22 '19 at 13:54

2 Answers2

3

You are only copying references in your cloning constructor, not creating a copy of the data. You will have to duplicate those arrays/collections.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

Maybe you can use a struct instead of a class?

But for your example, i would use ICloneable Interface.

Also, you can watch this discussion too.

Silviu
  • 56
  • 7