Are the objects copied using List <T> .Add or just "mapped"?
I ran into some kind of confusing behavior when using Lists
in C #. If I add a collection (I tested with List<T>
and Array
) of a given type in List
(i.e. List<List<int>>
), changing the child List
will also change the content of the parent List
to which it was added. However, if I add a non-collection object (i.e. bool
or int
) to List
, changing the object itself will NOT change the content List
to which it was added, I have provided a 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 example above, the collection is ints
just "mapped" to intList[0]
, so when you change the collection itself, ints
you also change intList[0]
because they are the same object. This contrasts with the following 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 example above, it seems that instead of being displayed on boolList[0]
, bigBool
COPIED on boolList[0]
. So, boolList[0]
is a copy bigBool
, and they are two separate objects.
So my question is, why are there apparently two separate functions List<T>.Add
, depending on what type is being added to List
? I checked MSDN but I couldn't find any mention of this behavior. Thank.
source to share
It depends on the type of object.
The value types will be copied. With reference types, reference will be used.
Integers, booleans, DateTime
are value types, for example (structs are value types) and string
, List<T>
are reference types (classes are reference types).
See Value Types and Reference Types on MSDN for more details .
source to share
Think of it as equality, just like:
var added = myObject;
If the object is a value type (like numbers, etc.) or immutable, for example string
, then it is copied. If it is a non-immutable reference type, like almost all instances of a class, then it simply gets another reference to the same object instance.
See below for a detailed description of MSDN:
source to share