Copy a generic list, List<>, by ref, by value wierdness
October 19, 2009 by: B.HardingHere is my latest weird problem.
I had a generic list, I wanted to make a copy of it. So the aproach I used was to make the new list = the first one.
Enter the wierdness; any mods to the second list showed up in the first one. So I guess it used a pointer or passed it by reference instead of making a copy like I expected.
Live and learn I guess. The work around was to initialize it blank and call the add range function passing it the first list.
Here is an example of what I’m talking about. You can past this into Linqpad as C# Statements and play around more.
List<string> s1 = new List<string>{“one”,“two”,“three”,“four”,“five”};
List<string> s2 = s1;
s2.Add(“six”);
s2.Add(“seven”);
s1.Dump();
s2.Dump();
List<string> s3 = new List<string>{};
s3.AddRange(s1);
s3.Add(“eight”);
s3.Add(“nine”);
s3.Add(“ten”);
s1.Dump();
s3.Dump();
Returns:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


