Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between the System.Array.CopyTo() and System.Array.Clone()

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

like image 410
Mister Dev Avatar asked Oct 13 '08 18:10

Mister Dev


People also ask

What is the difference between clone and copy?

clone - create something new based on something that exists. copying - copy from something that exists to something else (that also already exists).

What is difference between array and copy?

The main difference between a copy and a view of an array is that the copy is a new array, and the view is just a view of the original array. The copy owns the data and any changes made to the copy will not affect original array, and any changes made to the original array will not affect the copy.

How do I clone an array in C#?

The Clone() method in C# is used to clone the existing array. Firstly, set the array to be cloned. string[] arr = { "Web", "World"}; Now clone the array created above using the array.

What is the method MemberwiseClone () doing?

The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed.


1 Answers

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.

like image 53
Patrick Desjardins Avatar answered Sep 28 '22 06:09

Patrick Desjardins