Hello,
why does
List<Object> objectList; = some objects
List<Object> getList()
{
return objectList; //or return new List<Object>(objectList);
}
return a list with all items referenced to the original list's items?
Thanks.
Hello,
why does
List<Object> objectList; = some objects
List<Object> getList()
{
return objectList; //or return new List<Object>(objectList);
}
return a list with all items referenced to the original list's items?
Thanks.
You're returning a reference to ObjectList. : )
From MSDN: List<(Of <(T>)>)(IEnumerable<(Of <(T>)>))
Initializes a new instance of the List<(Of <(T>)>) class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.
In the first case you just return a reference to the list.
In the second case (new List<Object>(list)
) the objects are not copied: only the references are copied! You have to clone each item in the collection to return a deep copy of the list.
EDIT:
Iterate through your whole list and create a copy of each of your objects and put them into a new list.
See this for creating deep copies of custom objects. I would suggest not to use the interface ICloneable
. Make some research to learn why. :)
if you are using a custom object, Implement the ICloneable interface on the object.
Then, when you are returning your list, clone the objects into a new list. When you pass your old list into the constructor of your new list, you are passing references to all the objects in the original list, unless they are value type (string, int, etc)
Basically, because List<> and Object are reference types. If you read up on reference/value types in C# here: http://msdn.microsoft.com/en-us/library/3ewxz6et(v=VS.100).aspx it should make sense to you.