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 to share