tags:

views:

114

answers:

4

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.

+3  A: 

It is a reference

You're returning a reference to ObjectList. : )

AboutTheConstructor:

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.

SDReyes
even when using return new List<Object>(objectList); ?
byte1918
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. http://msdn.microsoft.com/en-us/library/d0cyc8ex.aspx : )
SDReyes
think of List<Object> like a list of pointers from c++ you are making new copies of the pointers not the object themselves.if this was a reference object like a List<int> it would behave as you are expecting.see http://www.albahari.com/valuevsreftypes.aspx
Scott Chamberlain
+13  A: 

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. :)

Simon
Thanks I get it now..
byte1918
A: 

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)

Lerxst
A: 

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.

Steve Dennis