posted on Wednesday, March 01, 2006 10:53 PM by johnwood

Cloning through Serialization

You don't have to implement ICloneable in order to clone objects. Any objects that are marked as serializable (by the [Serializable] attribute or implementing ISerializable) can also be effectively 'cloned' by serializing the object to a memory stream, and then deserializing back to a new copy of the original object.

I use this code to achieve this. You simply pass in the object that supports serialization and it returns a clone.

/// <summary>
/// Performs cloning through serialization
/// </summary>

public static object Clone(object obj)
{
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, obj);
    ms.Flush();
    ms.Seek(0, SeekOrigin.Begin);
    return bf.Deserialize(ms);
}

Perhaps you might find it useful too. 

Comments