Copy one array into a second array with CopyTo

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Code Snippets

C# Source Code Bank

See also …
edit

This C# code snippet copies an array into a second array beginning at a specified index using the CopyTo method of the Array class.

using System;
 
public class CopyToArray
{
   public static void Main()
   {
      object[] objects1 = {"one", "two", "three"};
      object[] objects2 = {0, 1, 2, 3, 4, 5};
      Console.Write ("objects1 array elements: ");
      foreach(object o in objects1)
      {
         Console.Write ("{0} ", o);
      }
      Console.Write ("\nobjects2 array elements: ");
      foreach (object o in objects2)
      {
         Console.Write ("{0} ", o);
      }
      objects1.CopyTo (objects2, 1);
      Console.Write ("\nobjects2 array elements: ");
      foreach (object o in objects2)
      {
         Console.Write ("{0} ", o);
      }
      Console.WriteLine();
   }
}


 Array.CopyTo example (program output)
objects1 array elements: one two three
objects2 array elements: 0 1 2 3 4 5
objects2 array elements: 0 one two three 4 5

Personal tools