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?
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?
No.
You can easily verify this by writing a small program to test.
Not strictly speaking, ICollection.ToArray()
creates a new T[]
and assigns each element in the original collection to the new array using Array.CopyTo()
.
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
© 2022 - 2024 — McMap. All rights reserved.