Array.Clone versus Array.CopyTo

  • Thread starter Thread starter james
  • Start date Start date
J

james

Hi Guys,

Would anyone mind telling me the difference between Array.Clone and
Array.CopyTo? I was asked this during an interview and got partial
credit for saying they were basically the same because they create
shallow copies. I ran ILDasm on Array and saw that they do the copy
using different IL calls. Does anyone know why one would be preferred
over the other?

Thanks,
James
 
Clone will return a new copy, CopyTo will copy the elements into an
array that you allocate.
 
Hi Guys,

Would anyone mind telling me the difference between Array.Clone and
Array.CopyTo? I was asked this during an interview and got partial
credit for saying they were basically the same because they create
shallow copies. I ran ILDasm on Array and saw that they do the copy
using different IL calls. Does anyone know why one would be preferred
over the other?

Thanks,
James

Hi,

Array.Clone creates a shallow copy of the array, whilst Array.CopyTo
copies all the elements of the array to the specified array
(preallocated).

With CopyTo you can copy the elements to the destination array
starting at a specified destination array index, thus add elements to
a given array.

Besides, as Nich mentioned, Clone does the allocation it self and
returns an exact length array.

Cheers,
Moty
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top