Shallow Copy vs DeepCopy in C#.NET
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; } } }
span.fullpost {display:none;}