1.

System.Array.CopyTo() vs System.Array.Clone() in C#

Answer»

Details about System.Array.CopyTo() and System.Array.Clone() are given as follows:

System.Array.CopyTo()

This method copies all the ELEMENTS that are in the current one-dimensional array into the one-dimensional array that is specified. The two parameters of the method are the array that is the destination array of the elements copied from the current array and the the index at which the array copying starts.

A program that DEMONSTRATES this is given as follows:

using System.IO; using System; class Demo {   public static void Main()   {      int[] source = new int[5] {6, 8, 1, 4, 7};      int[] target = new int[5];      source.CopyTo(target, 0);      Console.WriteLine("The target array is: ");      foreach (int i in target)      {          Console.WriteLine(i);      }   } }

The output of the above program is given as follows:

The target array is: 6 8 1 4 7

System.Array.Clone()

This method creates a shallow copy of the array and returns it. Also, the  System.Array.Clone() method is slower than the System.Array.CopyTo() method.

A program that demonstrates this is given as follows:

using System.IO; using System; class Demo {   public static void Main()   {      int[] source = new int[5] {6, 8, 1, 4, 7};      int[] target = new int[5];      target = (int[])source.Clone();      Console.WriteLine("The target array is: ");      foreach (int i in target)      {          Console.WriteLine(i);      }   } }

The output of the above program is given as follows:

The target array is: 6 8 1 4 7


Discussion

No Comment Found