snippetcsharpCritical
How do you do a deep copy of an object in .NET?
Viewed 0 times
netobjectyouhowdeepcopy
Problem
I want a true deep copy. In Java, this was easy, but how do you do it in C#?
Solution
Important Note
BinaryFormatter has been deprecated, and will no longer be available in .NET after November 2023. See BinaryFormatter Obsoletion Strategy
I've seen a few different approaches to this, but I use a generic utility method as such:
Notes:
-
Your class MUST be marked as
-
Your source file must include the following code:
BinaryFormatter has been deprecated, and will no longer be available in .NET after November 2023. See BinaryFormatter Obsoletion Strategy
I've seen a few different approaches to this, but I use a generic utility method as such:
public static T DeepClone(this T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}Notes:
-
Your class MUST be marked as
[Serializable] for this to work.-
Your source file must include the following code:
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;Code Snippets
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);
}
}using System.Runtime.Serialization.Formatters.Binary;
using System.IO;Context
Stack Overflow Q#129389, score: 735
Revisions (0)
No revisions yet.