I want a true deep copy. In Java, this was easy, but how do you do it in C#?
I'm still on the C# learning curve, but when I looked into this it appeared that you had to roll your own deep copy function if you wanted one.
I've seen a few different approaches to this, but I use a generic utility method as such:
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}
Note that your class MUST be marked as [Serializable] in order for this to work.
this is one way: http://www.thomashapp.com/node/106 another is to use binary serialization.
Have you tried using the struct construct? I'm a newbie to c# myself (also coming from the Java camp) but this may be useful to you.
http://www.c-sharpcorner.com/UploadFile/rajeshvs/StructuresInCS11112005234341PM/StructuresInCS.aspx
I.e.
With structs you can do this (psuedo code):
A = 10;
B = A;
B = 20
print(A) // out's 10
print(B) // out's 20
Kind of like java primatives, but structs can have methods and other variables just as regular classes
Kilhoffer's code doesn't compile. Here's the corrected version.
public static T DeepCopy<T>(T obj)
{
object result = null;
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
result = (T)formatter.Deserialize(ms);
ms.Close();
}
return (T)result;
}
Building on Kilhoffer's solution...
With C# 3.0 you can create an extension method as follows:
public static class ExtensionMethods
{
// Deep clone
public static T DeepClone<T>(this T a)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, a);
stream.Position = 0;
return (T) formatter.Deserialize(stream);
}
}
}
which extends any class that's been marked as [Serializable] with a DeepClone method
MyClass copy = obj.DeepClone();