Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

winforms

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?

like image 707
Gerbrand Avatar asked Dec 19 '25 00:12

Gerbrand


1 Answers

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()
    {
        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 that to a new List.

List<YourClass> originalItems = new List<YourClass>() { new YourClass() };
List<YourClass> newItemList = originalItems.Select(x => x.Clone() as YourClass).ToList();
like image 162
Stan R. Avatar answered Dec 21 '25 13:12

Stan R.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!