Labels

Saturday, September 27, 2008

Shallow Vs Deep Copy

Hi,

1. Shallow copy is done by the object method MemberwiseClone()

2. DeepCopy requires the classes to be flagged as [Serializable]

Shallow Copy

1. Value type --> A bit-by-bit copy of the field is performed

2. Reference type --> The reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object

Deep Copy

1. Value type --> A bit-by-bit copy of the field is performed

2. Reference type --> A new copy of the referred object is performed. Therefore, the original object and its clone refer to the seperate object

Code Snippet -

[Serializable]

public class CopyObject

{

// Note: The classes to be cloned (Deep Copy) must be flagged as [Serializable]. Therefore the CopyObject must be declared as 'Serializable'

public int Salary;

public CopyObject(int salary)

{

this.Salary = salary;

}

}

public class ShallowCopy

{

public static string CompanyName = "My Company";

public int Age;

public string EmployeeName;

public CopyObject Salary;

public ShallowCopy MakeShallowCopy(ShallowCopy inputcls)

{

return inputcls.MemberwiseClone() as ShallowCopy;

}

}

CopyObject clsref = new CopyObject(1000);

ShallowCopy m1 = new ShallowCopy();

m1.Age = 25;

m1.EmployeeName = "Ahmed Eid";

m1.Salary = new CopyObject(1000);;

ShallowCopy m2 = m1.MakeShallowCopy(m1);

m2.Salary.Salary = 2000; // Same Happens if you do it as - clsref.Salary = 2000;

ShowHideError("Salary: " + m1.Salary.Salary.ToString(), true);

[Serializable]

public class DeepCopy

{

public static string CompanyName = "My Company";

public int Age;

public string EmployeeName;

public CopyObject Salary;

public static T MakeDeepCopy<T>(T item)

{

BinaryFormatter formatter = new BinaryFormatter();

MemoryStream stream = new MemoryStream();

formatter.Serialize(stream, item);

stream.Seek(0, SeekOrigin.Begin);

T result = (T)formatter.Deserialize(stream);

stream.Close();

return result;

}

}

CopyObject clsref = new CopyObject(3000);

DeepCopy m1 = new DeepCopy();

m1.Age = 25;

m1.EmployeeName = "Ahmed Eid";

m1.Salary = clsref;

DeepCopy m2 = DeepCopy.MakeDeepCopy<DeepCopy>(m1);

m2.Salary.Salary = 4000; // Same Happens if you do it as - clsref.Salary = 2000;

ShowHideError("Salary: " + m1.Salary.Salary.ToString(), true);

Hope this helps.

Thanks & Regards,

Arun Manglick || Senior Tech Lead

No comments:

Post a Comment