Is there any difference between Array.Copy and CopyTo? Are they just overloaded?
5 Answers
Same functionality, different calling conventions. Copy is a static method, while CopyTo isn't.
Array.Copy(arraySrc, arrayDest, arraySrc.length);
arraySrc.CopyTo(arrayDest, startingIndex);
2 Comments
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 theSystem.Collections.ICollectioninterface. If implementingSystem.Collections.ICollectionis not explicitly required, useCopyto avoid an extra indirection.
Comments
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
- have better performance. (as husayt answered)
- instance method.
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, notmemcpy.
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
Array.Copy instead of Array.CopyTo. CopyTo is a different story.