Article Options
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:


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.


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.

Sponsored Links