Deep Copy in C#

This tutorial will introduce the method to create a deep copy of a class object in C#.

Deep Copy Object With the BinaryFormatter Class in C

Deep copy means copying every field of an object to another object, while shallow copy means creating a new class instance and pointing it to the previous class instance’s values. We can use the BinaryFormatter to create a deep copy of a class object in C#. The BinaryFormatter class reads and writes class objects to a stream in binary format. We can use the BinaryFormatter.Serialize() method to write our class object to a memory stream in C#. We can then write the same memory stream to an object with the BinaryFormatter.Deserialize() method and return it. We need to first mark our class with [Serializable] for this approach to work. The following code example shows us how to create a deep copy of an object with the BinaryFormatter class in C#.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace deep_copy
{
    [Serializable]
    public class Sample
    {
        public string sampleName { get; set; }
        
    }
    static class ext
    {
        public static Sample deepCopy<Sample>(this Sample obj)
        {
            using (var memStream = new MemoryStream())
            {
                var bFormatter = new BinaryFormatter();
                bFormatter.Serialize(memStream, obj);
                memStream.Position = 0;

                return (Sample)bFormatter.Deserialize(memStream);
            }
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Sample s1 = new Sample();
            s1.sampleName = "Sample number 1";
            Sample s2 = s1.deepCopy();
            Console.WriteLine("Sample 1 = {0}", s1.sampleName);
            Console.WriteLine("Sample 2 = {0}", s2.sampleName);
        }
    }
}

Output:

Sample 1 = Sample number 1
Sample 2 = Sample number 1

In the above code, we created a deep copy of the object s1 of the class Sample and saved it in the object s2 of the same class by using the BinarySerializer class in C#.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp Class

  • Pass Object by Reference in C#
  • Call Constructor From Another Constructor in C#