Click here to Skip to main content
15,921,169 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi , guys

I want to copy a list to another in C#. The problem is that existing methods like copyto creates a new list from another list. But if I make some changes to new list the old list also gets changed. Its because of their reference type behaviour. If there any way (apart from foreach loop) to create a new list from another list which will not reference the same object ?
i think the (AddRange) is the same !
even if elements of my list are reference types not only value type
Posted
Updated 7-Aug-13 3:42am
v2
Comments
Maciej Los 7-Aug-13 9:30am    
What about Marshal.Copy[^]?

1 solution

try this:

C#
List<int32> original = new List<int32>();
original.Add(1);
original.Add(2);

List<int32> copy = new List<int32>(original);
original.Add(3);
 
Share this answer
 
v2
Comments
Hamed_z 7-Aug-13 9:43am    
what about if elements of my list are reference types ?
Manas Bhardwaj 7-Aug-13 9:56am    
shouldn't be any different? Or I am missing anything?

List<List<string>> original = new List<List<string>>();
original.Add(new List<string>{"Manas", "bhardwaj"});
original.Add(new List<string>{"Manas1", "bhardwaj2"});

List<List<string>> copy = new List<List<string>>(original);
original.Add(new List<string>{"Manas3", "bhardwaj3"});

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