Saturday, November 13, 2010

Difference Between Shallow Copy and Deep Copy

Similarity :- Both are used to copying data between objects.

Shallow Copy :- Create a new object copy all non static field to new object. If field is value type a bit by bit copy has been performed. If the field is reference type, the reference is copied but the referred object is not. Therefore original object and clone object will refer to the same object. If you will change one object’s ref value other object will be change accordingly. But in case of value type will refer different object. Means if you will change one value other will not change. .Net provides a method MemberwiseClone() for the shallow copy.

private void DoAction()
{

CPerson objCPerson = new CPerson();

objCPerson.Age = 20;
objCPerson.Name =”Mohammad”;
objCPerson.Salary = new CSlary(1000);

CPerson objShallowCPerson = CreateShallowCopy();

objShallowCPerson.Age =25;
objShallowPerson.Name =”Ahmad”;
objCShallow.Slalary = new Slary(2000);

//If you will check original object

Print(“Age= “ + objCPerson.Age);
Print(“Name = ” + objCPerson.Name);
Print(“Salary = ” + objCPerson.Salary);

In case of Shallow Copy Output will be

Age = 20;
Name = Mohammad;
Salary = 2000;

//In case of Deep copy output will be

Output

Age = 20;
Name = Mohammad;
Salary = 1000;
}

public class CPerson : ICloneable
{
public string Name;
public int Age;
pulic CSalary objSalary=null;
;
public object Clone()
{
return this.MemberwiseClone();
}

public CPerson CreateShallowCopy(CPerson objCPerson)
{
return (CPerson)objCPerson.MemberwiseClone();
}

}


Deep Copy Everything is same except in case of reference type. A new copy of the referred object is perforemed. Therefore original and clone object will refer to different object. If you will change one object’s ref value other object remain unchanged.

The classes to be cloned must be flagged as [Serializable].

There is no direct method for deep copy in .Net . But can do it following way.

Example 1

[Serializable]
public class Person : ICloneable
{
public string Name;
public Person Spouse;
public object Clone()
{
Person p = new Person();
p.Name = this.Name;
if (this.Spouse != null)
p.Spouse = (Person)this.Spouse.Clone();
return p;
}
}

Example 2

[Serializable]
// serialize the classes in case of deep copy
public class clsDeep
{
public static string CompanyName = "My Company";
public int Age;
public string EmployeeName;
public clsRefSalary EmpSalary;
public clsDeep CreateDeepCopy(clsDeep inputcls)
{
MemoryStream m = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
b.Serialize(m, inputcls);
m.Position = 0;
return (clsDeep)b.Deserialize(m);
}
}

Deep Copy can be achieve by serialize the object.

Clone method is a method declared in ICloneable interface. and MemberwiseClone method is any objects inherit method that used for to create a shallow copy of an object.

No comments:

Followers

Link