#599 – Copying an Array Onto Another Array
June 6, 2012 Leave a comment
You can use the Array.CopyTo method to copy one entire array into another array. The first array must be the same size or smaller than the second array.
You specify the index into the second array where you want to start copying the first array. (0 indicates the first element of the second array). The portion of the second array starting at this index must be large enough to contain the entire first array.
static void Main() { int[] bigNumbers = {400, 500, 600}; int[] smallerNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Copy big number array into middle of small number array // Start at 4th element (index = 3) bigNumbers.CopyTo(smallerNumbers, 3); // Dump them both out DumpArrayContents(bigNumbers); DumpArrayContents(smallerNumbers); }
Note that if the portion of the destination array that starts at the specified index is not large enough to contain the source array, you will get an ArgumentException.
You can only use CopyTo with one-dimensional arrays.