An array is a contiguous memory allocation. It is used to store data collection of the same data types. Most of the time, we need to copy one array to another to perform computations without altering the original array. There are various ways to execute the copy operation, but in this Answer, we will compare Array.CopyTo()
and Array.Clone()
methods.
Array.CopyTo( )
methodThe CopyTo
method of the array class copies all the data in the array to an existing array. It performs a
The syntax of the CopyTo
method of the Array
class is:
Array.CopyTo(destArr, index);
Array
is the array we want to copy the contents.destArr
is the array of the same data type as Array
where the content will be copied to.index
is the integer from where we want to start copying on destArr
. The following is an example of copying array data to a new array using the CopyTo()
method.
class Educative{static void Main(){var arr1 = new[] { "Lodhi", "Educative", "Faheem", "Welcomes","You" };var arr2= new string[10];arr2[0]="Ed Tech";// cloning arr and storing it in new arrayarr1.CopyTo(arr2,1);// Printing array using loopforeach (var element in arr2){System.Console.WriteLine(element);}}}
arr1
of size 5.arr2
with a memory allocation of 10 indexes and assign the first index with a string "Ed Tech."copyto()
method of arr1
copying its elements to arr2
starting with index 1. arr2
.Array.Clone( )
method The Clone()
method of the Array
class copies all the data in the array and returns a new object. It needs to be typecast to the datatype of the original array. It performs a
The following is the syntax of the Clone()
method in C#:
(datatype[])array.Clone()
datatype[]
is the data type of the original array
. It needs to be array
is the array that we want to copy. Note: If you want to learn more about
Array.Clone()
method, check this answer.
An example of copying an array by using the Clone()
method is the following:
class Educative{static void Main(){var arr = new[] { "Lodhi", "Educative", "Faheem", "Welcomes","You" };// cloning arr and storing it in new arrayvar new_arr = (string[])arr.Clone();// Printing array using loopforeach (var element in new_arr){System.Console.WriteLine(element);}}}
Array.Copyto( ) | Array.Clone( ) |
Copyto( ) copies the source array to desitination array. | Clone() copies the array and returns the new object. |
It takes two parameters, that is, the destination array and index. | It takes a single parameter. |
It starts copying from the given index of the new array to the end of the array. | It always copies all content of the array. |
It is slightly slower because it is a wrapper of the copy method. | It is slightly faster. |
It does not need typecasting. | It needs to typecast the result to the original array datatype. |
Free Resources