#599 – Copying an Array Onto Another Array

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

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.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: