Copying arrays

suggest change

Copy part of an array with the static Array.Copy method, starting at index 0 in both the source and the destination:

var sourceArray = new int[] { 11, 12, 3, 5, 2, 9, 28, 17 };
var destinationArray= new int[3];
Array.Copy(sourceArray, destinationArray, 3);

// destinationArray will have 11,12 and 3

Copying the whole array with the CopyTo() instance method, beginning at index 0 of the source and the specified index in the destination:

var sourceArray = new int[] { 11, 12, 7 };
var destinationArray = new int[6];
sourceArray.CopyTo(destinationArray, 2);

// destinationArray will have 0, 0, 11, 12, 7 and 0

Clone is used to create a copy of an array object.

var sourceArray = new int[] { 11, 12, 7 };
var destinationArray = (int[])sourceArray.Clone();

// destinationArray is a new array containing 11, 12, and 7.

Both CopyTo and Clone perform a shallow copy. For an array of reference types, the new array holds the same object references as the original.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents