Hassan Mokdad Hassan Mokdad - 2 months ago 10
C# Question

What will happen to the items inside a shallow cloned list if the original list was cleared

My initial intention is to send list asynchronously through a TCP Stream. But directly after passing the list to the asynchronous thread I need to clear it to fill it again with new data. So I used Shallow cloning to create a copy of the list, and pass it to the background thread:

private List<MyDataObject> GetShallowCloneOfDataList(List<MyDataObject> dataEvents)
{
return new List<MyDataObject>(dataEvents);
}


and here is my final code:

List<MyDataObject> data = new List<MyDataObject>();
while(hasMoreData)
{
data.clear();
FillListFromServer(data);
List<MyDataObject> clonedList = GetShallowCloneOfDataList(data);
Task.Run(() => SendDataList(clonedList));
}


My question is, when I clear the original list
data
, will the items inside the cloned list be also affected? Testing my code revealed that they are not affected, but I am not sure if this will remain true when handling large amounts of data (200K per second).

Answer

No, the existing items aren't affected, other than being potentially eligible for garbage collection.

This is just like setting a variable to null, effectively:

MyDataObject x = new MyDataObject(); // And populate
MyDataObject y = x; // Just copy the reference
x = null; // This doesn't change either y or the data in the object

Another way of thinking about it is if you had an addressbook full of your friends and family's addresses, and then threw it on the fire... you wouldn't be able to find out where your friends and family were any more, but it wouldn't change where they lived. (See this answer for more on this kind of analogy.)