Shallow and Deep Cloning

Problem
You want to understand the difference between shallow and deep copies.

Solution
A shallow copy exists when a reference to a child object is copied as-is. A clone of the child object is not created. A deep copy exists when all child objects are cloned, and a separate copy of the entire object graph is created.

Comments
The difference between shallow and deep copies can be seen when an object has fields and properties that point to other objects. The ICloneable.Clone method returns a shallow copy of an object in most cases. However, you can change this behavior. You may determine that a deep copy is needed.

Example
You can perform a deep copy if the object and all its child objects are serializable.

public object CloneObject(object obj) {
    // Create a memory stream and formatter.
    MemoryStream memoryStream = new MemoryStream();
    BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));

    // Serialize the object into the stream.
    binaryFormatter.Serialize(memoryStream, obj);

    // De-serialize into a different object.
    object result = binaryFormatter.Deserialize(memoryStream);

    // Release the memory.
    memoryStream.Close();
    return result;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s