开发者

Strange behavior of Array.Clone()

开发者 https://www.devze.com 2023-02-13 11:30 出处:网络
I have a static array like below static byte[] myArray = {0x01,0x02}; I read that Array.clone does shallow copy.Then i execute the below codes.

I have a static array like below

static byte[] myArray = {0x01,0x02};

I read that Array.clone does shallow copy.Then i execute the below codes.

byte[] myArray2 = myArray.Clone() as byte[];
myArray2[0] = 0开发者_StackOverflow中文版x05;

But now Each myArray2[0] and myArray[0] contains different values.So I think Array.Clone() is performing a deep copy .Can you explain why?


byte is a primitive type, not a reference. Thus there is no difference between shallow and deep copy in this case.

Try using an array of a mutable object type, and you will notice the difference.

Update

but byte[] is a reference type right?

An array of a primitive type is deep down most probably represented by a contiguous block of memory, physically (by value) containing the elements. Whereas an array of an object type is a contiguous block of memory, containing only references to the actual elements (or nulls). Thus when you copy the array, in the first case you get a new array containing copies of the elements of the original. So after that, modifying an element in either of the arrays won't change the contents of the other array. Whereas in the second case you get a new array containing copies of the references in the original, still pointing to the same objects referred to by the original array elements. So if you modify any of the elements in either of the array, the change will be visible in the other array too.


A shallow copy means it copies the immediate values. If those values are pointers (reference types like objects in C#), then the pointers are copied over, and the values they point to (the state of the object) is not copied.

If the immediate values are primitives (ie: the value itself resides in the array, it's not referenced) then those values are copied. Hence the behavior is exactly as expected.

If you want to see the difference in your case, define an array of Objects.


Try this:

public class Person
{
    public string Name { get; set; }
}

Person person = new Person { Name = "Vaysage" };

Person[] persons1 = new Person[] { person  };

Person[] persons2 = (Person[])persons1.Clone();

persons2[0].Name = ".NET Junkie";

Assert.AreEqual(persons1[0].Name, ".NET Junkie");

The arrays are shallowly copied. This means that just references to the Person objects are copied and not the whole objects. Both arrays reference the same person object and thus the name of the person in the first array is changed as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号