tags:

views:

637

answers:

2

I've got a List and I used .copyTo() method. So it copies my List into one dimensional array.

So I loop this array and add each myObject to another List, then I'm changing things in this new List.

After this I'm showing the difference between the new values in my second List and the old values that are in my first List. But there is always no difference. So I'm thinking that the copyTo() method keeps a reference.

Are there other methods that doesn't keep a reference?

+2  A: 

If you've got a List of reference types, and you use the the CopyTo method to copy to an array, the contents of the List which are references will be copied across, so when you modify the objects in your array, they'll still refer to the same objects on the heap which are referenced from your list.

Charlie
That's my case. Are there other solutions for this?
Gerbrand
+4  A: 

Yes. .CopyTo() performs a shallow copy, which means it copies the references. What you need is a deep copy, by cloning each object.

The best way is to make you myObject class implement IClonable

public class YourClass 
{


    public object Clone()
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();

        bf.Serialize(ms, this);
        ms.Position = 0;

        object obj = bf.Deserialize(ms);
        ms.Close();

        return obj;
    }


}

Then you can cole .Clone() on each object and add that to a new List.

List<YourClass> originalItems = new List<YourClass>() { new YourClass() };
List<YourClass> newItemList = originalItems.Select(x => x.Clone() as YourClass).ToList();
Stan R.
So I have to add to my object the IClonable? and then the Clone method?
Gerbrand
Don't use `IClonable`, just write your own method that does the deep copy
John Rasch
@John. Thats fine too. Edited.
Stan R.
ok that works much better, thanks
Gerbrand