What is cloning and how we inpmement it in asp.net


In this article we are going to see what is cloning. What is the different types of cloning. what is deep and sallow copy. How can we use cloning in the asp.net. How can we implement cloning in the asp.net for cloning objects. How is it applied on value and reference types.

As we know cloning is done on Objects. If we need a copy of the object to do some changes to the existing state we use cloning.
It is performed mainly on array, collections or even in database.
Cloning is of 2 types:
1. Deep Copy
2. Shallow Copy
Shallow Clone
It makes a copy of object. If field is a value type then bit-bit copy of field is performed. If the field is referenc e type then only reference is copied.
System.Object is the namespace which contains a method MemberwiseClone() which can be used to implement Shallow cloning.
Deep Copy
It makes a copy of an object and also any references to the objects being maintained by the object. If the field is a reference type, it copies actual object to a new memory on managed heap.
*Any class that implements Icloneable interface supports cloning.


namespace CloningDemo
{
class Company
{
string companyname;
public Company(string companyname)
{
this.companyname = companyname;
}
public string CompanyName //property
{
get
{
return this.companyname;
}
set
{
this.companyname = value;
}
}
}
class Emp : ICloneable
{
//Clone the object, and returning a reference to a cloned object.

public int empid;
public Company c;
public Emp(int empid, Company c)
{
this.empid = empid;
this.c = new Company(c.CompanyName);
}
public void Show()
{
Console.WriteLine("Emp id is " + this.empid);
Console.WriteLine("Company name is " + this.c.CompanyName);
}

public object Clone()
{
//return this.MemberwiseClone(); //for shallow cloning

//for deep cloning
Emp e = new Emp(this.empid, new Company(this.c.CompanyName));
return e;
}

}
class Program
{
static void Main(string[] args)
{
Emp e1 = new Emp(1, new Company("SEED"));
Console.WriteLine("Details of e1:");
e1.Show();

Console.WriteLine();

Emp e2 = (Emp)e1.Clone();
Console.WriteLine("Details of e2 after cloning:");
e2.Show();

Console.WriteLine();

//change empid & companyname of e2
e2.empid = 999;
e2.c.CompanyName = "XYZ";
Console.WriteLine("Details of e1 after changing companyname of e2:");
e1.Show();
Console.ReadLine();
}
}
}

*MemberwiseClone() method creates a shallow copy by creating a new object and then copying the nonstatic fields of the current object to the new object.


Comments

Author: subhashini22 Jun 2011 Member Level: Silver   Points : 1

Hai sugandha,
I am new to this concept.This resource gives me an useful information.I am going to implement on project also.Thanks a lot.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: