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

Solution 1:

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.

Solution 2:

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.

Solution 3:

For Primitive Types you can do this:

List<string> CopyList = new List<string>(OriginalList);

For non-primitve/user-difined types you can do this:

List<Person> CopyList = new List<Person>();
foreach(var item in OriginalList)
{
    CopyList.Add(new Person { 
            Name = item.Name,
            Address = item.Address
    });
}

Solution 4:

name_list2 = new List<string>(name_list1); // Clone list into a different object

At this point, the two lists are different objects. You can add items to list2 without affecting list1

Solution 5:

The problem is the assignment. Until the assignment name_list2 = name_list1;, you have two different List objects on the heap pointed to by the variables name_list1 and name_list2. You fill up name_list1, which is fine. But the assignment says, "make name_list2 point to the same object on the heap as name_list1." The List that name_list2 used to point to is no longer accessible and will be garbage collected. What you really want is to copy the contents of name_list1 into name_list2. You can do this with List.AddRange. Note that this will result in a "shallow" copy, which is fine for the example you cite, where the list contents are strings, but may not be what you want when the list members are more complex objects. It all depends on your needs.