Array Copy in C#


Use the array. copy method in C# to copy a section of one array to another.

Our original array has 10 elements −

int [] n = new int[10]; /* n is an array of 10 integers */

Our new array that would copy a section of array 1 has 5 elements −

int [] m = new int[5]; /* m is an array of 5 integers */

The array.copy() method allow you to add the source and destination array. With that, include the size of the section of the first array that includes in the second array.

Example

You can try to run the following to implement Array copy in C# −

Live Demo

using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int [] n = new int[10]; /* n is an array of 10 integers */
         int [] m = new int[5]; /* m is an array of 5 integers */
         for ( int i = 0; i < 10; i++ ) {
            n[i] = i + 100;
         }
         Console.WriteLine("Original Array...");
         foreach (int j in n ) {
            int i = j-100;
            Console.WriteLine("Element[{0}] = {1}", i, j);
         }
         Array.Copy(n, 0, m, 0, 5);
         Console.WriteLine("New Array...");
         foreach (int res in m) {
            Console.WriteLine(res);
         }
         Console.ReadKey();
      }
   }
}

Output

Original Array...
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
New Array...
100
101
102
103
104

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 19-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements