tags:

views:

56

answers:

3

Hi ...

let's have this code :

class A : ICloneable 
{
    public int x = 2;
    public A(int x)
    {
       this.x = x; 
    }

    public A copy()
    {
        A a = new A(this.x);
        return a; 
    }

     public object Clone()
     {
         A a = new A(this.x);
         return a;
     }
}

In Main Method :

A[] Array1 = new A [4] ;
Array1[0] = new A(0);
Array1[1] = new A(1);
Array1[2] = new A(2);
Array1[3] = new A(3);
A [] Array2 = new A[10];
Array. Copy(Array1, Array2, 4); 

Array2[2].x = 11; 
for (int i = 0; i < 4; i++)
    Console.WriteLine(Array1[i].x); 

the output :

0

1

11

3

Although class A implements IClonable ...!! then .. what is the benefit of implement IClonable In Array ??

+2  A: 

Array.Copy copies the values of the array, in this case, references. There is nothing in the documentation of Array.Copy() that indicates a check for classes that implement IClonable and call Clone() instead. You will need to loop through the array and call Clone() yourself.

BTW, yes, IClonable kind of sucks.

Ed Swangren
+2  A: 

Array.Copy() does not use ICloneable. It simply copies values stored in each cell (which in this case are references to your A objects)

liho1eye
+2  A: 

From http://msdn.microsoft.com/en-us/library/k4yx47a1.aspx:

"If sourceArray and destinationArray are both reference-type arrays or are both arrays of type Object, a shallow copy is performed. A shallow copy of an Array is a new Array containing references to the same elements as the original Array. The elements themselves or anything referenced by the elements are not copied"

There may be a better method than this, but one technique you could use is:

  A[] array2 = array1.Select (a =>(A)a.Clone()).ToArray();
Ani