I have a bit of C# code which I use for performing a deep copy of an object:
public static T Copy<T>(T objectToCopy)
{
T result = default(T);
using (var memoryStream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, objectToCopy);
memoryStream.Seek(0, SeekOrigin.Begin);
result = (T)formatter.Deserialize(memoryStream);
memoryStream.Close();
}
return result;
}
I get this warning from Visual Studio:
Warning SYSLIB0011
'BinaryFormatter.Serialize(Stream)' is obsolete: 'BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.'
I get the same warning about BinaryFormatter.Deserialize(Stream)
.
I've looked at the suggested link, and they list some preferred alternatives:
XmlSerializer
andDataContractSerializer
to serialize object graphs into and from XML. Do not confuseDataContractSerializer
withNetDataContractSerializer
.BinaryReader
andBinaryWriter
for XML and JSON.- The
System.Text.Json
APIs to serialize object graphs into JSON.
I'm just struggling to figure out in my specific case how I would implement one of those alternatives.
If anyone could assist me in this I would greatly appreciate it.
Thank you.