Shallow and Deep Cloning

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

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.

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.

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.
    return result;

Leave a Reply

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

You are commenting using your 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