int[] array1 = new[] { 1, 2, 3 };
int[] array2 = (int[])array1.Clone();
array2[0] = 9;
Debug.Assert(array1[0] != array2[0]);
This works fine. Clone()
does a shallow copy, but the array types are value types, so they get cloned too.
My question is whether this is explicit in the language spec, or whether this is just an artifact of the current implementation?
My doubt is due to System.Array
supporting value types "invisibly" behind the scenes via run-time generics . Looking at the public methods you would expect value types to be boxed.
It works because there's absolutely no way two arrays could share the same instance of a value type.
The spec doesn't specifically say how
Array.Clone
behaves with value types vs how it behaves with reference types. But the spec does say that instances of value types are copied, bit-by-bit, on assignment. So whenarray1[i]
is copied toarray2[i]
, you get a clone of the instance at indexi
. Always.Keep in mind though, that if the value type has a field of a reference type, only the reference will be copied - not the instance of the reference type.
Even if
array1[i]
was boxed during the cloning, it would have to be unboxed so that you end up with aint[]
and not anobject[]
. The value would be cloned on unboxing.