Reputation: 35
Can anyone help explain why we get this result? What I expected result is "1,2".
var list1 = new List<int> { 1, 2 };
List<List<int>> listStrs = new List<List<int>> { new List<int>{100,101 }, new List<int>{ 200, 201 } };
foreach (var listStr in listStrs)
{
List<int> list2 = list1; //the way try to get expected result: List<int> list2 = list1.Select(i => i).ToList();
list2.AddRange(listStr);
}
Console.WriteLine(String.Join(",",list1));
//result return: 1,2,100,101,200,201
Upvotes: 1
Views: 527
Reputation: 32750
List<T>
is a reference type. When you do the following:
List<int> list2 = list1;
What you are actually doing is telling the compiler to make a copy of the value of the variable list1
and assign it to list2
. You must understand that variables are simply placeholders for values. In reference types, the value of the variable is the "address in memory" where the object "lives". Therefore, both list2
and list1
are "pointing" to (or referencing) the exact same object; there are two variables but one single list.
This is made obvious simply doing: object.ReferenceEquals(list1, list2)
. It will return true
.
List<int> list2 = list1.Select(i => i).ToList();
works as you expect because the projection (Select
) creates a new list. This new list and list1
are altogether different instances and each "live" in different memory locations and are unrelated altogether; object.ReferenceEquals(list1, list2)
wil return false
.
Now, do bear in mind, that things change with value types. The value "stored" in a value typed variable is the instance itself; there are no references when it comes to value types (unless they are boxed).
Therefore, the following code:
struct EvilMutableStruct
{
public int i
}
var e1 = new EvilMutableStruct();
var e2 = e1;
e2.i = 1;
Console.WriteLine(e1.i == 1); //prints false!
Why? Because, again, e2 = e1
means the same; make a copy of the value stored in e1
and assign it to e2
. Because the value of e1
is the value type instance itself, a copy of the object is made and stored in e2
. Now both value typed variables hold two identical but distinct value type instances.
Upvotes: 1