O'Reilly logo

C# Primer: A Practical Approach by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

4.7. Mastering Copy Semantics: ICloneable

When we copy one reference type with another, as in the following example:

Matrix mat = new Matrix( 4, 4 );
// ...
Matrix mat2 = mat;

the result is a shallow copy; that is, both mat and mat2 now refer to the same Matrix object on the managed heap. A problem occurs when the object is modified through one handle, as in this example:

// changes are seen through mat2 as well
mat[0,0]=mat[1,1]=mat[2,2]=mat[3,3]=1;

while the second handle still requires the object to be in its original state.

If we are users, we cannot modify the class implementation to provide deep-copy semantics. Rather we'll need to explicitly implement a deep copy. First we allocate a new instance of the reference types. Next we copy ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required