Ankit
Ankit

Reputation: 6153

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 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 ?

Upvotes: 0

Views: 126

Answers (4)

Alen.Toma
Alen.Toma

Reputation: 4870

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

Upvotes: -1

Aaron Roberts
Aaron Roberts

Reputation: 1372

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);
    }
}

Upvotes: 1

Gilad Green
Gilad Green

Reputation: 37281

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?

Upvotes: 0

Richard
Richard

Reputation: 109160

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

Upvotes: 2

Related Questions