Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Framework  »  Copying vs. Cloning  »  Investigation
Copying vs. Cloning
by Phil Eakins | Published  02/09/2006 | .NET Framework | Rating:
Investigation

Introduction

In order to investigate the various methods of obtaining a copy of an array, I wrote a short program (the VS 2003 source code can be downloaded from the link) and systematically worked my way through copying or cloning both System and User Designed Types. 

These tests also introduce the concept of a ‘deep copy’, which means that a copy of any Object Type must be a completely independent copy of that Object. Everything directly or indirectly referenced by any field in that Object must also be copied.

A true deep copy was thought, by me at least, to be difficult to attain as it would have to be implemented on an object-by object basis, and only then so long as each object’s Type implemented the IClonable interface. However, Richter & Balena suggested a remedy using Streams. Balena enhanced the method in "Programming Microsoft Visual Basic .NET Version 2003" (MS Press 2004, ISBN 0-7356-2059-8) and is substantially used in the following tests as 'CloneObject'. The catch, of course, is that the objects in the Array being deep copied by this technique must each support Serialisation, as must each Object referred to by them.

Preparation

The following tables list the tests that were carried out on arrays of either Type in order to establish the effectiveness of producing a truly independent copy of that array.

The test of System Types is implemented by creating Array1() and filling it with appropriate data.  Array1() is then copied to Array2() using the selected method.

Array1() is altered using the method shown in Table 1 and the arrays are then compared for independence.

A list of the data used are shown in Appendix 1.

The Person Class, which supports both Clone and CloneObject methods, was subclassed into PetOwner and Team Classes.

The PetOwner Object can have a reference to a Pet Object, which does not have a Clone Method, or a SecondPet Object, which does.

Team Objects have no references.

Array1() is filled with one of the Person Objects, see Appendix 1.  Array1() is copied to Array2() using the chosen method, and then altered by changing Person, Pet or Team data as detailed in Appendix 1.  The arrays are then compared.

 

Sponsored Links