How to deep-copy/clone an object

The easiest way to deep copy an object is to serialize and deserialize it. Here’s an example from a project I’m working on:

[Serializable()]
public class Board :ICloneable, ISerializable {

    // ...

    object ICloneable.Clone()
    {
        return this.Clone();
    }

    public Board Clone()
    {
        using (var ms = new MemoryStream())
        {
            var bf = new BinaryFormatter();
            bf.Serialize(ms, this);
            ms.Position = 0;
            return (Board)bf.Deserialize(ms);
        }
    }

You might need to implement the serialization functions too for this to work, however.

Posted in

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *