I’ve come across some confusing behavior while using Lists in C#. If I add a collection (I’ve tested with both List<T> and Array) of a given type to a List (i.e. List<List<int>>), modifying the child List will also modify the contents of the parent List to which it was added. However, if I add an object that isn’t a collection (i.e. a bool or an int) to a List, modifying the object itself will NOT modify the contents of the List to which it was added. I’ve included some sample code below:
List<List<int>> intList = new List<List<int>>();
List<int> ints = new List<int>();
ints.Add(12345);
intList.Add(ints);
Console.WriteLine(intList[0].Count); //intList[0].Count is 1
ints.Clear();
Console.WriteLine(intList[0].Count); //intList[0].Count is 0
It seems that in the above example, the ints collection is simply “mapped” to intList[0], so when you modify the ints collection itself, you are also modifying intList[0], because they are the same object. This contrasts with the next example:
List<bool> boolList = new List<bool>();
bool bigBool = false;
boolList.Add(bigBool);
Console.WriteLine(boolList[0]); //boolList[0] is false
bigBool = true;
Console.WriteLine(boolList[0]); //boolList[0] is...still false??
In the above example, it seems that rather than being mapped to boolList[0], bigBool is COPIED to boolList[0]. So boolList[0] is a copy of bigBool, and they are two separate objects.
So my question is: why do there seem to be two separate functionalities of List<T>.Add, depending on what type is being added to the List? I’ve checked MSDN, but I couldn’t find any mention of this behavior. Thanks.
It depends on the kind of object.
Value types will be copied. With reference types the reference will be used.
Integers, booleans,
DateTimeare value types, for example (structs are value types) andstring,List<T>are reference types (classes are reference types).See Value Types and Reference Types on MSDN for details.