How can I create a deep clone without using 'BinaryFormatter'?

Viewed 2128

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 and DataContractSerializer to serialize object graphs into and from XML. Do not confuse DataContractSerializer with NetDataContractSerializer.
  • BinaryReader and BinaryWriter 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.

0 Answers
Related