System.ArrayCopyTo() vs System.ArrayClone() in C#


The ArrayCopyTo() method copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. The index is specified as a 32-bit integer.

The CopyTo() method in C# is used to copy elements of one array to another array. In this method, you can set the starting index from where you want to copy from the source array.

The following is an example showing the usage of CopyTo(,) method of array class in C# −

Example

using System;

class Program {
   static void Main() {
      int[] arrSource = new int[4];
      arrSource[0] = 5;
      arrSource[1] = 9;
      arrSource[2] = 1;
      arrSource[3] = 3;

      int[] arrTarget = new int[4];

      // CopyTo() method
      arrSource.CopyTo(arrTarget,0 );

      Console.WriteLine("Destination Array ...");
      foreach (int value in arrTarget) {
         Console.WriteLine(value);
      }
   }
}

Array.Clone() method in C# clones the array. Here, we have a string array −

Example

using System;

class Program {
   static void Main() {
      string[] arr = { "one", "two", "three", "four", "five" };
      string[] arrCloned = arr.Clone() as string[];

      Console.WriteLine(string.Join(",", arr));

      // cloned array
      Console.WriteLine(string.Join(",", arrCloned));
      Console.WriteLine();
   }
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 21-Jun-2020

44 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements