Clone
|
CopyTo
|
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. |
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. |
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;i<array2.Length;i++) {
Console.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;i<array2.Length;i++) {
Console.Write(array2[i]+" ");
}
}
}
Output of this code will be:
10 20 30
|