Shallow Copy vs DeepCopy in C#.NET

Posted on Microsoft .NET Support Team See other posts from Microsoft .NET Support Team
Published on Sat, 27 Mar 2010 19:49:00 +0000 Indexed on 2011/01/11 9:58 UTC
Read the original article Hit count: 276

Hope below example helps to understand the difference. Please drop a comment if any doubts.

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

namespace ShallowCopyVsDeepCopy
{
    class Program
    {
        static void Main(string[] args)
        {
            var e1 = new Emp { EmpNo = 10, EmpName = "Smith", Department = new Dep { DeptNo = 100, DeptName = "Finance" } };
            var e2 = e1.ShallowClone();
            e1.Department.DeptName = "Accounts";
            Console.WriteLine(e2.Department.DeptName);

            var e3 = new Emp { EmpNo = 10, EmpName = "Smith", Department = new Dep { DeptNo = 100, DeptName = "Finance" } };
            var e4 = e3.DeepClone();
            e3.Department.DeptName = "Accounts";
            Console.WriteLine(e4.Department.DeptName);
        }
    }

    [Serializable]
    class Dep
    {
        public int DeptNo { get; set; }
        public String DeptName { get; set; }
    }

    [Serializable]
    class Emp
    {
        public int EmpNo { get; set; }
        public String EmpName { get; set; }
        public Dep Department { get; set; }

        public Emp ShallowClone()
        {
            return (Emp)this.MemberwiseClone();
        }

        public Emp DeepClone()
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(ms, this);
            ms.Seek(0, SeekOrigin.Begin);
            object copy = bf.Deserialize(ms);
            ms.Close();

            return copy as Emp;
        }
    }
}

© Microsoft .NET Support Team or respective owner

Related posts about .NET Tips and Tricks

Related posts about collections