.NET by Patrik

Direct List Assignment Issue

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.

Comments (1)

qyYmFTeuio

9/15/2024 5:53:55 AM
YhFITutD

Leave a Comment

All fields are required. Your email address will not be published.