Array.Clone() performs deep copy instead of shallow copy

I've read that Array.Clone performs shallow copy, however this code suggests that a deep copy of the original array is created ie any changes in cloned array are not being reflected in original array

int[] arr = new int[] { 99, 98, 92, 97, 95 };
int[] newArr = (int[])arr.Clone();
//because this is a shallow copy newArr should refer arr
newArr[0] = 100;
//expected result 100
Console.WriteLine(arr[0]);//print 99

Am i missing something obvious here ?


When copying a collection of immutable structs (primitives such as it's are immutables) there is no difference between deep and shallow copy. They are copied by value - and therefore it is as deep copy performs.

See more for the difference under: What is the difference between a deep copy and a shallow copy?


because this is a shallow copy newArr should refer arr

Nope, the array and its elements are copied. But references to objects in the elements are not copied.

The copy goes down just one level: hence shallow. A deep copy would clone all referenced objects (but this cannot be shown with ints.)


Try the same code but with a class that has a property that is an integer. Since the array elements are value types the elements of the cloned array are their own "instances".

example:

class SomeClass {
    public Int32 SomeProperty { get; set; }
}

SomeClass[] arr = new [] {
    new SomeClass { SomeProperty = 99 },
    new SomeClass { SomeProperty = 98 },
    new SomeClass { SomeProperty = 92 },
    new SomeClass { SomeProperty = 97 },
    new SomeClass { SomeProperty = 95 }
}

SomeClass[] newArr = (SomeClass[])arr.Clone();

newArr[0].SomeProperty = 100;

Console.WriteLine(arr[0].SomeProperty);
链接地址: http://www.djcxy.com/p/40802.html

上一篇: 使用LINQ to SQL管理子列表

下一篇: Array.Clone()执行深层复制而不是浅拷贝