1

Since windows phone does not have the System.Runtime.Serialization.Formatters.Binary namespace, i am using the following way:

bool[][] newMask = (bool[][])this.mask.Clone();

But i am not sure whether this will make a deep copy or not (although this question suggests that i will make a deep copy but my suspicion lies on the fact that i am using a jagged array for performance purpose)

Community
  • 1
  • 1
Ali Zahid
  • 1,329
  • 2
  • 17
  • 23
  • Greetings and welcome to SO! Please don't include tags in the title. I've edited your title accordingly. – tnw Oct 08 '13 at 15:58

2 Answers2

4

That only makes a shallow copy. To make a deep copy, you'd want something like:

bool[][] newMask = new bool[mask.Length][];
for (int i = 0; i < newMask.Length; i++)
{
    newMask[i] = (bool[]) mask[i].Clone();
}

From the docs for Array.Clone:

Creates a shallow copy of the Array.

...

A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

It will not make a deep copy. Or to be more precise, it will do a deep copy of outer array only. But because you have an array of arrays (and array is a reference type), references to inner arrays will be copied to new outer array.

Proof

var source = new int[1][];
source[0] = new int[2];
source[0][0] = 0;
source[0][1] = 1;

var copy = (int[][])source.Clone();

copy[0][0] = 2;
Console.WriteLine(source[0][0]);

Prints 2 instead of 0.

You can do real deep clone using LINQ:

// without Clone() method
var copy = source.Select(x => x.ToArray()).ToArray();

// or with Clone() method
var copy = source.Select(x => (int[])x.Clone()).ToArray();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263