Home >Backend Development >C++ >How to Deep Copy a List in C# to Avoid Shared References?
Simply using new List<Book>(books_1)
to clone a List<T>
in C# doesn't create a completely independent copy. Changes to the cloned list will also affect the original list because they share references to the underlying objects.
To achieve a true deep copy, ensuring that modifications to the cloned list don't impact the original, use the following technique:
<code class="language-csharp">List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));</code>
This code iterates through each Book
object in the original list (books_1
). For each object, it creates a new Book
object using a constructor (implied here, assuming Book
has a constructor that takes title
as an argument). These newly created Book
objects are then added to a new list (books_2
). This guarantees that books_2
contains entirely independent copies of the data from books_1
.
The above is the detailed content of How to Deep Copy a List in C# to Avoid Shared References?. For more information, please follow other related articles on the PHP Chinese website!