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 identical object.
So the difference are :
1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.
Edit:
Remove the wrong example.
One other difference not mentioned so far is that
- with
Clone()
the destination array need not exist yet since a new one is created from scratch. - with
CopyTo()
not only does the destination array need to already exist, it needs to be large enough to hold all the elements in the source array from the index you specify as the destination.
As stated in many other answers both methods perform shallow copies of the array. However there are differences and recommendations that have not been addressed yet and that are highlighted in the following lists.
Characteristics of System.Array.Clone
:
- Tests, using .NET 4.0, show that it is slower than
CopyTo
probably because it usesObject.MemberwiseClone
; - Requires casting the result to the appropriate type;
- The resulting array has the same length as the source.
Characteristics of System.Array.CopyTo
:
- Is faster than
Clone
when copying to array of same type; - It calls into
Array.Copy
inheriting is capabilities, being the most useful ones:- Can box value type elements into reference type elements, for example, copying an
int[]
array into anobject[]
; - Can unbox reference type elements into value type elements, for example, copying a
object[]
array of boxedint
into anint[]
; - Can perform widening conversions on value types, for example, copying a
int[]
into along[]
. - Can downcast elements, for example, copying a
Stream[]
array into aMemoryStream[]
(if any element in source array is not convertible toMemoryStream
an exception is thrown).
- Can box value type elements into reference type elements, for example, copying an
- Allows to copy the source to a target array that has a length greater than the source.
Also note, these methods are made available to support ICloneable
and ICollection
, so if you are dealing with variables of array types you should not use Clone
or CopyTo
and instead use Array.Copy
or Array.ConstrainedCopy
. The constrained copy assures that if the copy operation cannot complete successful then the target array state is not corrupted.