Published · 1 min read

How to copy Array values by value and not by reference.

When you try to copy the value of one Array into another, you actually end up having two references to the same array. This is because an Array is a reference type.

When you try to copy the value of one Array into another, you actually end up having two references to the same array. This is because an Array is a reference type.

int[] A = { 1, 2, 3 };
int[] B = A;
B[1] = 69;
Console.WriteLine(A[1]);

The above code would give an output of 69. As you can see, changes made to the elements of array B are applied to those of array A.

To do a copy by value you need to iterate through each of the Array elements in the source array and assign the value to the corresponding index in the destination array.

int[] A = { 1, 2, 3 };

// Set the Size of Array B to be the same as that of Array A.
int[] B = new int[A.Length];
for (int I = 0; I < A.Length; I++)
{
    B[I] = A[I];
}

There is a much simpler way to do this using the static method Copy of the Abstract class Array.

int[] A = { 1, 2, 3 };

// Set the Size of Array B to be the same as that of Array A.
int[] B = new int[Arr.Length];
Array.Copy(A, 0, B, 0, Arr.Length);

The Copy method is overloaded into 4 forms with two variations:-

Array.Copy(int[] SourceArray, int[] DestinationArray, int NumberOfElementsToCopy);
Array.Copy(int[] SourceArray, int SourceIndexToStartCopyFrom,
int[] DestinationArray, int DestinationIndextToStartCopyFrom, int NumberOfElementsToCopy);

The remaining two forms are the long counterparts of these two.

Partho Sarathi

Partho Sarathi

Founder, Maxotek

C# & .NET

Our blog

Related posts

Tutorials, notes and news from Maxotek.

View all posts

See what Maxotek makes

Monitoring, conversion tools and more, built by the same people who wrote these posts.