Home > Google > How to copy Array values by value and not by reference.

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

October 28th, 2007

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.

1
2
3
4
5
6
7
8
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 Google

  1. sanjib Kumar Pal
    January 28th, 2008 at 13:50 | #1

    Hi sanjib Kumar pl… see

  1. No trackbacks yet.