Here I have an example for a deep copy, which deeply copies all reference type objects that are used with a copy constructor:
public sealed class MyGame
{
private int start;
private Board board;
public MyGame(MyGame orig)
{
// value types - like integers - can easily be
// reused
this.start = orig.start;
// reference types must be clones seperately, you
// must not use orig.board directly here
this.board = new Board(orig.board);
}
}
public sealed class Board
{
private int count;
public Board(Board orig)
{
// here we have a value type again
this.count = orig.count;
// here we have no reference types. if we did
// we'd have to clone them too, as above
}
}
I think your copy might be somehow shallow and re-use some references (like for instance this.board = orig.board
instead of creating a new board). This is a guess though, as I can't see your cloning implementation.
Furthermore, I used copy constructors instead of implementing ICloneable
. The implementation is almost the same. One advantage though is that you simplify dealing with subclasses:
Suppose you had a MyAwesomeGame : MyGame
, not overriding MyGame.Clone
. What would you get from myAwesomeGame.Clone()
? Actually, still a new MyGame
because MyGame.Clone
is the method in charge. One may carelessly expect a properly cloned MyAwesomeGame
here, however. new MyGame(myAwesomeGame)
still copies somehow incompletely, but it's more obvious. In my example I made the classes sealed
to avoid this failures. If you can seal them, there's good change it will make your life simpler.
Implementing ICloneable
is not recommended in general, see Why should I implement ICloneable in c#? for more detailed and general information.
Here I have an ICloneable
approach anyway, to make things complete and enable you to compare and contrast:
public class MyGame : ICloneable
{
private int start;
private Board board;
public object Clone()
{
var copy = new MyGame();
copy.start = this.start;
copy.board = (Board)this.board.Clone();
return copy;
}
}
public class Board : ICloneable
{
private int count;
public object Clone()
{
var copy = new Board();
copy.count = this.count;
return copy;
}
}