Cloning an object using serialization

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.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.