In c# does Array.ToArray() perform a DEEP copy?
Asked Answered
S

2

8

This should be a pretty basic question, but I've been having a little trouble finding a definite answer.

When you have an array of values and you use the .ToArray() method does it create a deep or shallow copy of the array?

Salas answered 30/4, 2012 at 16:49 Comment(1)
I was actually looking for an answer to this on the internet before I wrote a quick test for it (which is not as quick as googling). I think the reason for the -1 rating on the question is just because of you're misunderstanding between Deep copy, Shallow copy, and object referencing (what you're probably referring to as shallow copy).Quinnquinol
W
11

No.

You can easily verify this by writing a small program to test.

Widely answered 30/4, 2012 at 16:50 Comment(6)
+1. Note that if it is array of struct it will copy values (still shallow copy).Leu
I just created a small program with a string[] with 3 elements in it, I then created a new array with = origArray.ToArray() I then changed one element in the new array and printed out both arrays and they where different, doesn't this mean it is a deep copy? what am I over looking?Salas
There is no built in way to make deep copy in C#, so probably your definition of "deep" is unusual. Consider asking new question "what is deep copy, here is my understanding..." (don't forget to clearly explain how you understand it so other people can confirm/comment on what part of your understanding is wrong OR non-traditional).Leu
Thanks, I will do a little more research first (and maybe ask another question), It was my understanding that with shallow copy the original object and its clone refer to the same object, so if I change the new object it would also change what the original one sees. And then I thought deep didn't do that (that it made an entirely new object)Salas
@Salas the reason your test showed what it did is strings in C# are immutable - what you actually did is re-assign a new string to the element at that index in your other array - to test a deep copy create an array of your own classes with a reference type variable then modify that variable on one element in one array and you will see you modified it in both arraysMooncalf
this answer could use more explanation and detailLouannlouanna
L
8

Not strictly speaking, ICollection.ToArray() creates a new T[] and assigns each element in the original collection to the new array using Array.CopyTo().

Note:

If T is a value type, values are assigned and not references. This will behave as one would expect of a "Deep" copy.

int[] foo = { 1, 2, 3, 4 };
int[] bar = foo.ToArray();

for (int i = 0; i < foo.Length; i++) foo[i] += 10;

Console.WriteLine(string.Join(',', foo)); // 11, 12, 13, 14
Console.WriteLine(string.Join(',', bar)); // 1, 2, 3, 4
Louannlouanna answered 13/12, 2020 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.