Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Folks,

Below code snippet is adding a list to anothe list.


List
XML
<string> str1 = new List<string> { "A",   "A", "B", "C", "D", "A", "B", "C", "D", };
            List<string> str2 = new List<string> { "A", "A", "B", "C"};

            str1.AddRange(str2);

I am curios to know how the memory allocation will happen in this case.

1) Will str1 contains 11 element and 11th element will be pointing to str2
Or
Str1 will contain 15 element.
Posted
Comments
_Asif_ 23-Jun-14 8:57am    
Can't you see yourself by opening watch window and see the allocations?

No, str1 will contain 13 elements:
A
A
B
C
D
A
B
C
D
A
A
B
C
There were 9 before, and you added 4: 9 + 4 == 13
 
Share this answer
 
The AddRange method copies all the items found in another enumerable. The original list named str2 can be changed and even be collected and it will not affect the contents of str1 after the call to AddRange.

In fact, the AddRange is very similar to:
C#
foreach(var value in str2)
  str1.Add(value);


But even if it is very similar, it is actually faster in many situations as it can do a single validation/inner array resize for all the items that will be added while the Add will do those validations per call.
 
Share this answer
 
Comments
vickyanand25005 23-Jun-14 13:47pm    
Thanks Paulo this make sense.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900