简体   繁体   中英

Is System.Array.Clone() guaranteed to clone value types?

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 when array1[i] is copied to array2[i] , you get a clone of the instance at index i . 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.

my query was whether potential boxing by Array would negate this. ie the boxed references are copied rather than the underlying value type.

Even if array1[i] was boxed during the cloning, it would have to be unboxed so that you end up with a int[] and not an object[] . The value would be cloned on unboxing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM