.NET by Patrik

Avoiding List Reference Issues in .NET: Making Independent Copies

In .NET, when you assign one list (list2) to another list (list1) directly, both lists will reference the same memory location. As a result, any modifications made to list2 will also affect list1. To create a separate copy of the list, you should use the List<T> constructor to initialize a new list based on the elements of the original list (list1).

...see more

To illustrate the issue the following code assigns list1 directly to list2.

List<string> list1 = new List<string>();
List<string> list2 = list1;

list2.Add("Item A");

Console.WriteLine("List1 elements:");
list1.ForEach(item => Console.WriteLine(item));

This will output the list1 elements and show 'Item A'.

List1 elements:
Item A

As you can see, modifying list2 also modified list1.

Explanation of direct assignment issue

When you assign one list to another using list2 = list1, you're not creating a new list. Instead, both list1 and list2 will point to the same list in memory. Any changes made to one list will be reflected in the other because they are essentially the same list.

...see more

The following code shows modifying of list2 does not affect list1 because list2 is a separate copy of list1.

List<string> list1 = new List<string>();
List<string> list2 = new List<string>(list1);

list2.Add("Item A");

Console.WriteLine("List1 elements:");
list1.ForEach(item => Console.WriteLine(item));

This will output list1 without any item.

List1 elements:

Explanation of copying the List

You can use the List<T> constructor with the original list as an argument to create a new list that is a separate copy of the original list. This constructor creates a new list with the same elements as the original list.

Comments