8.23.2012

Difference between Clone and CopyTo methods in .NET

Difference between Clone and CopyTo methods in .NET

S.No
Clone
CopyTo
1
Clone method returns a new array containing all elements copied from the array on which clone method is called.
CopyTo method copies elements of the array into an existing array. Elements will be copied into a specific index and its increments.
2
The array size of the destination array need not be mentioned.
Array size of the destination array has to be declared before triggering copyTo method.
3
If the array size declared is smaller to fit in elements, the array size will automatically grow based on the number of elements that are getting copied.
Array size should be large enough to fit both existing array elements and the elements to be copied. If the size is smaller than the actual number of elements, then you will get the following error while performing CopyTo:
"Destination array was not long enough. Check destIndex and length, and the array's lower bounds."

Here is an example of Clone method:

class sampleClass{
public static void Main() {
int[] array1 = new int[] {10,20,30};
int[] array2 = array1.Clone() as int[];
for(int i=0;iConsole.Write(array2[i]+" ");
}
}
}
Output of this code will be:
10 20 30

Here is an example of CopyTo method:
 
class sampleClass{
public static void Main() {
int[] array1 = new int[] {10,20,30};
int[] array2 =
new int[array1.Length];
array1.CopyTo(array2,0);
for(int i=0;iConsole.Write(array2[i]+" ");
}
}
}
Output of this code will be:
10 20 30

Note: Both the Clone and CopyTo methods belong to System.Array namespace.

No comments:

Post a Comment