Simply add
[System.Serializable]
attribute to the class that you wish to Serialize.
Feel free to add these to your extensions
public static byte[] Clone<T>(this T a)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, a);
return stream.ToArray();
}
}
public static T FromClone<T>(this byte[] array)
{
using (MemoryStream stream = new MemoryStream(array))
{
BinaryFormatter formatter = new BinaryFormatter();
return (T)formatter.Deserialize(stream);
}
}
Now you should be able to save the Clone and load an instance of cloned class from file.
As you wish sir.
public static class Helper { public static T CreateDeepCopy<t>(T obj) { using (var ms = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(ms); } } }
From here: https://levelup.gitconnected.com/5-ways-to-clone-an-object-in-c-d1374ec28efa
One thing that you will see using BinaryFormatter is that the output can get exceptionally large. I will provide 2 more helpers to help you compress them using System.IO.Compression
public static byte[] CompressClone<T>(this T a)
{
byte[] clone = a.Clone<T>();
using (var compressedStream = new MemoryStream())
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
zipStream.Write(clone, 0, clone.Length);
zipStream.Close();
return compressedStream.ToArray();
}
}
public static T DecompressClone<T>(this byte[] array)
{
byte[] clone = null;
using (var compressedStream = new MemoryStream(array))
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
clone = resultStream.ToArray();
}
return clone.FromClone<T>();
}