By Kamran Shakil
Like finalize() method, we also come to see memberwiseclone() method in
almost every class ,as protected instance methods . It is inherited from Object class,
which is the mother class of .NET classes..
By definition, memberwiseclone() method "creates a shallow copy of the current
Object."
A shallow copy of an Object is a copy of the Object only. If the Object contains
references to other objects, the shallow copy will not create copies of the referred
objects. It will refer to the original objects instead. On the other hand, a deep copy
of an object creates a copy of the object and a copy of everything directly or
indirectly referenced by that object.
This can be explained using an example i.e, suppose X is an Object with references
to the objects A and B, and the object A also has a reference to an object M, a
shallow copy of X is an object Y, which also has references to objects A and B. On
the other hand, a deep copy of X is an object Y with direct references to objects C
and D, and an indirect reference to object N, where C is a copy of A, D is a copy of B,
and N is a copy of M.
In C Sharp we write as:
protected object MemberwiseClone();
In VB.NET we, write as:
Protected Function MemberwiseClone() As Object
In Managed C++ we, write as:
protected: Object* MemberwiseClone();
This method cannot be overridden; a subclass should implement the ICloneable
interface if a shallow copy is not appropriate.The ICloneable interface contains one
member, Clone, which is intended to support cloning beyond that supplied by
MemberwiseClone.
It is to be remembered that Object Class contains not only memberwise clone
method but, there are other method also, like object self constructor, finalize method
and some public instance methods.
Happy .NETing!
Regards.