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;
}
}
}
Post a Comment
a bit of explaination ought to be there. otherwise it is alos good
It does work. but if the class has an event that some other class handles it, this it will also be copy, and you can not mark it as nonserialize.
Still; it works very very slowly!!