Search code examples
c#generic-collections

Why is my Collection<T> working differently to my List<T> class when copying?


I want to copy a collection and add new elements to only one of them (not both).

In the code example below I copy the collection by creating a new one and passing it in the constructor. After that I add an element in only one of the collections. After that both collections contains the new element...

var listOne = new Collection<Test>();

listOne.Add(new Test());
listOne.Add(new Test());

var listTwo = new Collection<Test>(listOne);

listOne.Add(new Test());

Console.WriteLine(listOne.Count); // 3
Console.WriteLine(listTwo.Count); // 3 (NOT OK)

When I use a List instead of a Collection it works as expected.

var listOne = new List<Test>();

listOne.Add(new Test());
listOne.Add(new Test());

var listTwo = new List<Test>(listOne);

listOne.Add(new Test());

Console.WriteLine(listOne.Count); // 3
Console.WriteLine(listTwo.Count); // 2 (OK)

In both cases I expect that the second list only contains 2 elements. Why is there a difference between a Collection and a List?


Solution

  • When you look into the source code, you see that a collection doesn't copy the given collection's content. It just references the given collection as its own items.

    The list's constructor adds the given collection's items to its own items store.