Information Technology Reference
In-Depth Information
The Clone Method
The Clone method performs a shallow copy of an array. This means that it only creates a clone
of the array itself. If it is a reference type array, it does not copy the objects referenced by the
elements. This has different results for value type arrays and reference type arrays.
￿
Cloning a value type array results in two independent arrays.
￿
Cloning a reference type array results in two arrays pointing at the same objects.
The Clone method returns a reference of type object , which must be cast to the array type.
int[] intArr1 = { 1, 2, 3 };
Array type Returns object
int[] intArr2 = ( int[] ) intArr1.Clone();
For example, the following code shows an example of cloning a value type array, produc-
ing two independent arrays. Figure 14-16 illustrates the steps shown in the code.
static void Main()
{
int[] intArr1 = { 1, 2, 3 }; // Step 1
int[] intArr2 = (int[]) intArr1.Clone(); // Step 2
intArr2[0] = 100; intArr2[1] = 200; intArr2[2] = 300; // Step 3
}
Figure 14-16. Cloning a value type array produces two independent arrays.
Search WWH ::




Custom Search