Home >Backend Development >C++ >How Do I Perform a Deep Copy of Objects in .NET?
Unlike Java, achieving a true deep copy of an object in .NET requires a different approach. This guide outlines effective methods for creating deep copies.
The BinaryFormatter
class provides a robust solution for deep copying in C#. This serialization class converts an object into a binary stream, which is then deserialized to generate a new, independent object instance.
A generic utility method simplifies the deep cloning process:
<code class="language-csharp">public static T DeepClone<T>(this T obj) { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T)formatter.Deserialize(ms); } }</code>
The target class must be decorated with the [Serializable]
attribute.
Ensure the following using
statements are included in your source file:
<code class="language-csharp">using System.Runtime.Serialization.Formatters.Binary; using System.IO;</code>
The above is the detailed content of How Do I Perform a Deep Copy of Objects in .NET?. For more information, please follow other related articles on the PHP Chinese website!