Thursday 17 May 2012

What's the difference between the System.Array.CopyTo() and System.Array.Clone()?

The Clone() method returns a new array (a shallow copy) object
containing all the elements in the original array. The CopyTo() method
copies the elements into another existing array. Both perform a
shallow copy. A shallow copy means the contents (each array element)
contains references to the same object as the elements in the original
array. A deep copy (which neither of these methods performs) would
create a new instance of each element's object, resulting in a
different, yet identacle object.






Here are the differences:

MyArrayList2 = MyArrayList;

This will just copy the reference to MyArrayList into MyArrayList2. If
you add an element to MyArrayList2, then you will see that in MyArrayList,
because they both point to the same thing.

MyArrayList2 = MyArrayList.Clone();

This will create a shallow copy of the ArrayList. If the elements are a
reference, then those references are copied. If they are value types, then
that is copied to the new array list. Now, if they are all reference types,
then the two array lists are pointing to the same objects. However, if you
add a new item to MyArrayList2, then it will not be shown in MyArrayList,
because MyArrayList2 is a new object, not a reference to the same
MyArrayList.

No comments:

Post a Comment