This post will discuss how to create a deep copy of a List in C#.

1. Using Constructor

You can use a constructor to create a copy of objects in C#. To create a deep copy of a list of objects, you can iterate through the list and create a copy of each item by invoking its constructor. This approach is can be used if the class is not complex and contains few properties. A typical implementation of this approach would look like below using the Select() or ConvertAll() method:

Download  Run Code

Output:

[Olivia, 10], [Robert, 20], [John, 15]
[Olivia, 10], [Robert, 20], [John, 15]

 
C# had made it possible to write simpler and concise code. Starting with C#9, you can take advantage of the new with expression if your object contains many fields. The with expression can create a copy of any record with an arbitrary number of its init-only properties modified. The following code example demonstrates its usage:

Download  Run Code

Output:

[Olivia, 10], [Robert, 20], [John, 15]

2. Using Clone() method

Alternatively, you can implement your own Clone() method to facilitate a field-for-field copy of a class. Then you can simply loop over the list and clone each item by invoking the Clone() method, as shown below:

Download  Run Code

Output:

[Olivia, 10], [Robert, 20], [John, 15]

3. Using Serializable() Method

Finally, you can use serialization to serialize an object into a MemoryStream and then deserialize it back. To indicate that instances of a class can be serialized, apply the SerializableAttribute attribute. The following example demonstrates the serialization of a List of objects.

Download  Run Code

Output:

[Olivia, 10], [Robert, 20], [John, 15]

That’s all about creating a deep copy of a List in C#.