SoFunction
Updated on 2025-03-07

Several methods of copying arrays in C# (summary)

I suddenly learned it, so I put it on the blog and shared it, just treat it as a study diary.

First of all, let me explain that the array is of reference type, so be careful not to copy the address without copying the value when copying!

In fact, when copying an array, you must use new to open a new space in the heap to store the array specifically, which is effective.

(1)

int[] pins = { 9, 3, 7, 2 };

int[] copy=new int[];

     for (int i = 0; i < ; i++)

     {

       copy[i] = pins[i];

   }

(2)

int[] copy = new int[];

(copy, 0);

(3)

Int[] pins= new int[4]{9,3,7,2};

Int[] alias=pins;

Note that this kind of copying is just a reference, it just passes the address of the data to the alias array, so it is not recommended to copy the array in this way;

(4)

(pins,copy,)

(5)

Int[] copy=(int[])();

Here I explain why the cast type of int[] is used. The reason is that the result type of Clone is object, so it needs to be cast to int[]

The Object class is actually the base class of all our classes.

The above several methods (summary) of C# copy arrays are all the content I share with you. I hope you can give you a reference and I hope you can support me more.