Home >Backend Development >C++ >How to Deep Copy a List in C# to Avoid Shared References?

How to Deep Copy a List in C# to Avoid Shared References?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-11 18:26:46303browse

How to Deep Copy a List in C# to Avoid Shared References?

Creating a True Deep Copy of a C# List

The Challenge

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.

The Solution: A Deep Copy Approach

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn