.Net - Frequently Asked Questions
System.Array.CopyTo VS. System.Array.Clone()
Both System.Array.CopyTo and System.Array.Clone() are methods in C# that allow you to create a copy of an array, but they have some important differences.
System.Array.CopyTo
- CopyTo is a void method that copies the elements of an array to another array or a section of it.
- It requires a destination array to be provided as a parameter, and the elements from the source array are copied to the destination array starting from the specified index.
- It performs a shallow copy, which means that if the elements in the source array are reference types, the references are copied rather than creating new instances of the objects.
- The destination array must have sufficient capacity to accommodate the copied elements.
Example:
int[] sourceArray = { 1, 2, 3, 4, 5 };
int[] destinationArray = new int[5];
sourceArray.CopyTo(destinationArray, 0);
System.Array.Clone()
- Clone() is a method that creates a shallow copy of the array.
- It returns a new array object that is a replica of the original array, with the same length and containing the same elements.
- It performs a shallow copy, just like CopyTo, where the references to the objects are copied instead of creating new instances.
- The returned array is a separate object in memory, independent of the original array.
int[] originalArray = { 1, 2, 3, 4, 5 };
int[] clonedArray = (int[])originalArray.Clone();
While both CopyTo and Clone() create copies of an array, CopyTo requires a destination array to be provided and performs the copy operation, while Clone() creates a new array object with the same elements as the original array. Both methods perform shallow copies, meaning they copy references to objects rather than creating new instances.
Related Topics