views:

75

answers:

1

Assuming I have a List<Stuff> listA that has some items in it. I create a second list as follows:

List<Stuff> listB = new List<Stuff>(listA);

Let's say I have an item from listA, and I try to remove it from listB:

Stuff itemFromA = listA[0];
listB.Remove(itemFromA);

Assuming Stuff is a Class, should the item be successfully removed from listB? In other words, are the members the same objects or does the process of creating a new list clone the items?

I am experiencing behaviour in some code I'm debugging where the .Remove fails to remove the item from listB.

+9  A: 

The List<T> Constructor (IEnumerable<T>) does not clone the items.

For value types the value is copied, for reference types a reference to the same object is added to the list.

List<object> listA = new List<object>();
listA.Add(new object());

List<object> listB = new List<object>(listA);
bool result = object.ReferenceEquals(listA[0], listB[0]);

// result == true
dtb
Unless T is a struct, where the value is copied, not referenced.
codekaizen
Great thanks, that's what I thought as well. There must be some other code behind the scenes thats causing the .Remove to fail then, cheers!
jerry
codekaizen - yeah I suspected that too but checked and its class. thanks as well
jerry