C# Language Arrays Copying arrays

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Copying a partial array with the static Array.Copy() method, beginning at index 0 in both, source and 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 will be created and will have 11,12,17.

Both CopyTo and Clone perform shallow copy which means the contents contains references to the same object as the elements in the original array.



Got any C# Language Question?