Middle
What is the difference between Clone and CopyTo methods for arrays in C#?
sobes.tech AI
Answer from AI
Clone creates a shallow copy of an array, returning a new array instance with elements of the same type. If the array elements are reference types, only the references to the objects are copied, not the objects themselves.
CopyTo copies elements from the current array to another existing array, starting at the specified index. The target array must be sufficiently long.
// Example of using Clone
int[] originalArray1 = { 1, 2, 3 };
int[] clonedArray = (int[])originalArray1.Clone();
// clonedArray is now { 1, 2, 3 }
// Example of using CopyTo
int[] originalArray2 = { 4, 5, 6 };
int[] destinationArray = new int[5];
originalArray2.CopyTo(destinationArray, 1); // Copy into destinationArray starting at index 1
// destinationArray is now { 0, 4, 5, 6, 0 }
Main differences:
- Purpose: Clone creates a new array, while CopyTo fills an existing array.
- Return value: Clone returns an Object (requires casting), CopyTo has a void type.
- Shallow copy: Both methods perform a shallow copy.
- Flexibility: CopyTo allows specifying the starting index in the target array.
// Example with reference types
class MyObject
{
public int Value { get; set; }
}
MyObject[] originalObjects = { new MyObject { Value = 1 }, new MyObject { Value = 2 } };
// Clone
MyObject[] clonedObjects = (MyObject[])originalObjects.Clone();
clonedObjects[0].Value = 10; // Change in clone affects the original object
// originalObjects[0].Value is now 10
// CopyTo
MyObject[] copiedObjects = new MyObject[2];
originalObjects.CopyTo(copiedObjects, 0);
copiedObjects[0].Value = 20; // Change in copy also affects the original object
// originalObjects[0].Value is now 20