C # List <myObject> myList.copyTo () keeps reference?

I have a List and I used the .copyTo () method. So it copies my list into one dimensioned array.

So, I will loop this array and add each myObject to a different list, then change things in that new list.

After that, I show 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 think the copyTo () method keeps the reference.

Are there other methods that do not maintain the link?

+2


source to share


2 answers


Yes..CopyTo () does a shallow copy, which means it copies the links. You need a deep copy by cloning every object.

The best way is to make you a myObject class that implements IClonable

public class YourClass 
{
    public object Clone()
    {
        using (var ms = new MemoryStream())
        {
           var 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 it to the new list.

List<YourClass> originalItems = new List<YourClass>() { new YourClass() };
List<YourClass> newItemList = originalItems.Select(x => x.Clone() as YourClass).ToList();

      

+8


source


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



+2


source







All Articles