Archive

Archive for December, 2005

Cloning an object using serialization

December 13th, 2005 No comments

Here’s an easy way of cloning an object (deep copy):

public T CloneObject<T>(T obj) where T:class
{
    if (obj== null)
        return null;

    MemoryStream memstream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(memstream, obj);
    memstream.Seek(0, SeekOrigin.Begin);
    T clone = (T)formatter.Deserialize(memstream);
    memstream.Close();
    return clone;
}

The requirement is of course that the object is serializable and marked with the [Serializable] attribute.

Categories: .Net programming Tags:

Switch to our mobile site

Web Analytics