Hi there,
The example that you gave would result in Array variables
A and
B pointing to the same array (and therefore the same objects). The code below proves this:
-
-
// Declare and initialise array A
-
Object[,] A;
-
A = new Object[10, 10];
-
-
// Set a value
-
A[2, 4] = "Hi there";
-
-
// Declare another array, B
-
Object[,] B;
-
-
// Set B's reference to array A (shallow copy - same as Clone())
-
B = A;
-
-
// Array variables A and B now point to the same array,
-
// and therefore, the same objects.
-
-
Console.WriteLine("A[2,4]={0}\nB[2,4]={1}",
-
A[2, 4], B[2, 4]);
-
-
// Change a value in A
-
A[2, 4] = "A new value";
-
-
// See if the value in A has affected
-
// the value in B.
-
Console.WriteLine("A[2,4]={0}\nB[2,4]={1}",
-
A[2, 4], B[2, 4]);
-
-
// Do the references of A and B match?
-
Console.WriteLine("Does A[2,4] reference "
-
+ "the same object as B[2,4]? Answer={0}",
-
(Object.ReferenceEquals(A[2, 4], B[2, 4])
-
== true) ? "Yes" : "No");
-
-
Arrays are
reference types (not
Value types). Reference types simply
refer to objects, they do not hold the value of an object. Thus in the example, assigning
B with the value of
A simply means that
B is assigned a copy of
A's reference to an array. They both then refer to the same array.
It is important to understand that variable
B is not provided with a fresh stand alone copy of the array that variable
A refers to. Both variables now refer to the same array and thus the same objects in the array.
The only way to get a completely stand alone copy of a two-dimensional array and its elements is to manually copy every element in the array to a new array.
Be careful when hand copying array elements. If the array holds value types (such as int, long, char etc) then simply assigning them to a location in the new array will work fine. However, if (like in the example above) the array contains reference types (Objects) then obtaining a shallow copy of each element raises the same problem as the array copy issue - i.e. you'll be copying the references to objects and not copying the objects themselves.
Each object in the array will have to be
DEEP copied using ICloneable interface.
I refer you to:
http://www.thescripts.com/forum/thread233829.html
Hope this helps a bit.