Article Options
Recently Viewed
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Framework  »  Copying vs. Cloning  »  Why Didn't the Copy Command Work?
Copying vs. Cloning
by Phil Eakins | Published  02/09/2006 | .NET Framework | Rating:
Why Didn't the Copy Command Work?

Looking at Figure 1, Char is a Value Type and hasn't been Boxed, so its copy should behave independently.  But (and it's a big but) the Array Type is a Reference Type, it doesn't matter that the content of the array is of Value Type.  The array contents are still placed on the Heap with a pointer on the Stack.

Thus, when I thought I'd copied the array, I'd actually copied the pointer to it.  This diagram should make it clearer:

Cloning

Many Framework Objects include a Clone method - whether that method will produce a truly independant copy of an array depends very upon the content of the array.  in this case:

will produce an independent copy of Array1() as the content is of Value Type.  The result will be of Object Type.  It must be cast to the correct Type (in this case Char) as I have done here, using DirectCast as the clone is a Reference Type.

Confusion!

The MS documentation* says that Cloning produces a 'shallow' copy - but in this case it produced a different sort of shallow copy than when the Copy command is used.  Confused?  I was, which is why I set about compiling a comparison of the different ways of copying the content of arrays.

Comments    Submit Comment

Comment #1  (Posted by an unknown user on 02/09/2006)
Rating
Fantastic in-depth coverage of a topic that would otherwise frustrate people when they ran in to such problems.

Thanks!
 
Comment #2  (Posted by an unknown user on 02/28/2006)
Rating
It is Good
 
Comment #3  (Posted by an unknown user on 03/23/2006)
Rating
really excellent
 
Comment #4  (Posted by Rob Mrowiec on 06/20/2006)
Rating
This was a very good explanation of the topic of Cloning and what should be considered when deciding to copy or clone. Now if only someone would just remove all the weeds in the search engines so that it is easier to find this article!
 
Comment #5  (Posted by an unknown user on 07/23/2006)
Rating
Thank you for your in depth knowledge
Very helpful!
 
Comment #6  (Posted by an unknown user on 10/30/2006)
Rating
this definitely a very nice detailed explanation
 
Comment #7  (Posted by an unknown user on 11/03/2006)
Rating
great
 
Comment #8  (Posted by an unknown user on 12/01/2008)
Rating
orsitac
 
Sponsored Links