If I create a new List<T> from an existing list, are the members equal?
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 wor开发者_运维知识库ds, 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
.
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
精彩评论