Wednesday, October 31, 2007

Assigning and Copying Arrays

Arrays are Reference Types

This means that the data in the object is stored somewhere in the computer's memory and the variable holds a pointer to that area of memory. If one object variable is assigned to another, only the pointer to the memory location is duplicated; both variables actually point to the same data. A change in one object's values is therefore reflected in the other object.

This can be demonstrated by assigning one array to another. A change to any of the elements of either array is visible in both:

int[] primary = new int[] {2,4,8};

// Point a second array at the same memory range using assignment
int[] secondary = primary;

// Retrieve a value from the primary array
int value = primary[1]; // value = 4

// Alter the value in the secondary array and re-read the primary
secondary[1] = 99;
value = primary[1]; // value = 99

It is important to understand the effects of assigning reference types as mistakenly modifying one instance can unexpectedly cause problems elsewhere.

Cloning Arrays

It is often necessary to create a copy of an array that may be manipulated without damaging the contents of the original. To achieve this, the array class includes a Clone method. Rather than assigning a simple reference, this creates a completely new copy of the array. The Clone method returns an object but the specific array type is not specified so this object must be cast to the correct type for assignment.

int[] primary = new int[] {2,4,8};

// Clone the array into a secondary array, casting appropriately
int[] secondary = (int[])primary.Clone();

// Retrieve a value from the primary array
int value = primary[1]; // value = 4

// Alter the value in the secondary array and re-read the primary
secondary[1] = 99;
value = primary[1]; // value = 4
value = secondary[1]; // value = 99