Introduction
The purpose of this article is to explain the concepts of shallow copy and deep copy using a Student class.
class Student
{
public int Id = 0;
}
Understanding
Shallow Copy
Shallow Copy duplicates as little as possible. A shallow copy of a collection is similar to two collections sharing the same elements.
Student adam = new Student();
adam.Id = 10;
Student eve = adam;
adam.Id = 5; // <-- If you see value of eve.Id after this line, it will be 5.
See this.MemberwiseClone()
Deep Copy
Deep copy duplicates everything. A deep copy of a collection is similar to two separate copy of collections.
Student adam = new Student();
adam.Id = 10;
Student eve = new Student();
eve.Id = adam.Id;
adam.Id = 5; // <-- If you see value of eve.Id after this line, it will be 10.
Remarks
Clone
A shallow copy retains the original references of the elements. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.
In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.
ICloneable Interface
The ICloneable
interface simply requires that your implementation of the Clone()
method return a copy of the current object instance. It does not specify whether the cloning operation performs a deep copy, a shallow copy, or something in between. Nor does it require all property values of the original instance to be copied to the new instance. For example, the Clone()
method performs a shallow copy of all properties except the IsReadOnly
property; it always sets this property value to false in the cloned object. Because callers of Clone()
cannot depend on the method performing a predictable cloning operation, we recommend that ICloneable
not be implemented in public APIs.