4

Is there any difference between Array.Copy and CopyTo? Are they just overloaded?

5 Answers 5

9

Same functionality, different calling conventions. Copy is a static method, while CopyTo isn't.

Array.Copy(arraySrc, arrayDest, arraySrc.length);
arraySrc.CopyTo(arrayDest, startingIndex);
Sign up to request clarification or add additional context in comments.

2 Comments

Popester: you have given a wrong syntax. syntax for copy is Array.Copy(srcarray,destarray,srcarray.length); and also for copyto mehod: srcarray.CopyTo(destarray, destarray_index); more details refer msdn.microsoft.com/en-us/library/system.array.aspx
What Gmathipriya says is right: it should be: arraySrc.CopyTo(arrayDest, arrayDest.StartIndex);
7

Look at it carefully. Copy is a static method whereas CopyTo is an instance method.

Comments

7

But they are not only convention-wise different; there is a key functional difference.

Here is an excerpt from MSDN:

This method (Array.CopyTo) supports the System.Collections.ICollection interface. If implementing System.Collections.ICollection is not explicitly required, use Copy to avoid an extra indirection.

Comments

1

Comparing
https://msdn.microsoft.com/en-us/library/k4yx47a1.aspx and
https://msdn.microsoft.com/en-us/library/06x742cw.aspx,
We will see that:

Array.CopyTo

  • able to copy multidimensional arrays.
  • easier to specify range to be copied.
  • static method.

CopyTo

And there are something I am not sure that, the remarks of Array.CopyTo said:

This method is equivalent to the standard C/C++ function memmove, not memcpy.

Which CopyTo do not have such description.
It is true that it is not easy to copy part of an array to it self using CopyTo without parameters to control range. Still, you could use ArraySegment or array.Skip(offset).Take(length) to achieve it.
And in my test, there is no problem to do so.

1 Comment

It's a mistake that got me wild goose chasing. Please somebody edit the answer, I tried twice at different times and couldn't. It's Array.Copy instead of Array.CopyTo. CopyTo is a different story.
0

Functionally, I don't know if there is anything different between the two other than the CopyTo method will copy all elements of the array and Copy will allow you to specify a range of elements to copy

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.