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

135 views Asked by At

I've read that Array.Clone performs shallow copy, however this code suggests that a deep copy of the original array is created i.e. 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 ?

4

There are 4 answers

2
Gilad Green On BEST ANSWER

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?

0
Alen.Toma On

In some advanced Array or List<> is really hard to only use Array.Clone() use instead a plugin like FastDeepCloner which I developed. It will clone the object intrusively.

var newArr= FastDeepCloner.DeepCloner.Clone(arr);
0
Aaron Roberts On

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 (DotNet Fiddle):

using System;
                    
public class Program
{
    class SomeClass {
   
        public Int32 SomeProperty { get; set; }

    }
    
    public static void Main()
    {
        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);
    }
}
0
Richard On

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.)