Hi
What is the difference between the System.Array.CopyTo() and System.Array.Clone() ?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh TrivediPosted Jun 27, 2012, 11:38 PM
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array.
http://msdn.microsoft.com/en-us/library/system.array.clone.aspx
http://msdn.microsoft.com/en-us/library/system.array.copyto.aspx
int[] Originalnumbers = { 1, 2, 3, 4, 5 };
int[] numbersClone = (int[])Originalnumbers.Clone();
numbersClone[2] = 0;
Console.WriteLine("Clone Example");
Console.WriteLine("----------------------");
Console.WriteLine(Originalnumbers[2]);//Display 4
Console.WriteLine(numbersClone[2]);//Display 0 !!! Not the same :)
Console.WriteLine("----------------------");
int[] numbersCopy = new int[6];
Originalnumbers.CopyTo(numbersCopy, 0);
numbersCopy[3] = 0;
Console.WriteLine("Copy Example");
Console.WriteLine("----------------------");
Console.WriteLine(Originalnumbers[3]);//Display 4
Console.WriteLine(numbersCopy[3]);//Display 0 !!! Not the same :)
Console.WriteLine("----------------------");
hope this will help you.
VulpesPosted Jun 27, 2012, 12:04 PM