Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign List<T> without it being a reference to the original List<T>?

Tags:

c#

reference

For example

List<string> name_list1 = new List<string>(); List<string> name_list2 = new List<string>(); 

later in the code:

name_list1.Add("McDonald"); name_list1.Add("Harveys"); name_list1.Add("Wendys");  name_list2 = name_list1; // I make a copy of namelist1 to namelist2 

So, from this point I would like to keep adding element or making changes in name_list2 without affecting name_list1. How do I do that?

like image 379
TheScholar Avatar asked Nov 19 '12 03:11

TheScholar


People also ask

How do I assign one list to another in C#?

To add the contents of one list to another list which already exists, you can use: targetList. AddRange(sourceList); If you're just wanting to create a new copy of the list, see the top answer.

Are lists passed by reference?

Lists are already passed by reference, in that all Python names are references, and list objects are mutable. Use slice assignment instead of normal assignment.

How do I copy one collection to another in C#?

What you will need to do is iterate over one list, crate a new object, copy the property values over, and add it to the other list.


2 Answers

Another Options is : Deep Cloning

public static T DeepCopy<T>(T item)         {             BinaryFormatter formatter = new BinaryFormatter();             MemoryStream stream = new MemoryStream();             formatter.Serialize(stream, item);             stream.Seek(0, SeekOrigin.Begin);             T result = (T)formatter.Deserialize(stream);             stream.Close();             return result;         } 

so,

you can use :

name_list2 = DeepCopy<List<string>>(name_list1); 

OR:

name_list2 = DeepCopy(name_list1);  

will also work.

like image 40
ayc Avatar answered Oct 07 '22 11:10

ayc


name_list2 = new List<string>(name_list1); 

This will clone the list.

Edit: This solution only works for primitive types. For objects, see other responses below.

like image 70
Inisheer Avatar answered Oct 07 '22 11:10

Inisheer