tags:

views:

60

answers:

4

Hi I wrote the code below :

1. MyClass[] origArr=new MyClass[3];  
2. MyClass[] arr1;
3. // filled the array with objects and did some work on it .  
4. dgv_1.DataSource=origArr;  
5. 
6. // Here is the problem :
7. arr1=origArr;  
8. // do some work on arr1 ...  
9. dgv_2.DataSource=arr1;  

For some reason the data in 'origArr' changed when data in 'arr1' change ...
I thought that maybe this happened because 'origArr' and 'arr1' are pointers referring to the same object so I changed line '7' to :

7. origArr.CopyTo(arr1,0);

but it didn't work ... what can i do to make the pointers referring to different objects?

+7  A: 

Your line 7 copies the reference to origArr into arr1, so they point to the same physical array.

Even a Clone or CopyTo won't help much: you will get a copy of the array structure, but in there the references to your oringinal classes are copied. So you end up with a new array with still the same objects.

You will need to Clone your MyClass objects and put those clones into a new array.

Hans Kesting
Many thanx for u .. as i understood i declared 'arr1' as @Andrey said and made a for loop and created a new MyClass() object with the same values in 'origArr' : arr1=new MyClass() { MyProp=orig[i].Myprop };and it worked ... i hope that this the right way to do it .
Al0NE
Yes that will work: by copying all properties, you make an independent clone of the original MyClass.
Hans Kesting
+2  A: 

In c# variable holds reference, not the value. to copy it do

MyClass[] origArr=new MyClass[3];  
MyClass[] arr1 = new MyClass[3];
origArr.CopyTo(arr1,0);

you have to allocate memory by yourself

Andrey
thanx for answering , but didn't work too .
Al0NE
what do you mean it didn't work? please be specific. i tried, it works.
Andrey
this is the code i tried it : Class1[] a = new Class1[3]; for (int i = 0; i < a.Length; i++) { a[i] = new Class1(); a[i].MyProperty = i; } Class1[] b = new Class1[3]; a.CopyTo(b, 0); b[1].MyProperty = 6;but it gives the same result as my code...changes happened in both arrays.
Al0NE
so follow first answer about cloning
Andrey
+1  A: 

You need to change line 7 to origArr.CopyTo(arr1,0); as you noted. But you also need to initialize the arr1 array.

1. MyClass[] origArr=new MyClass[3];   
2. MyClass[] arr1=new MyClass[3];  
Matthew Whited
+1  A: 

try to use

Array.Copy(src , dest, lenght)

CoffeeCode