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 ...
Get C# Primer: A Practical Approach now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.