Pages

Search

Monday, February 20, 2012

Cloning an Object

Cloning an object is not same as just like applying equal to operator.
Both the ways copy happens but it is differed like shallow copy and Deep copy.
Using equal to operator, a new reference will be created but the created reference still points the same object or memory block (reference pointers are also copied). This is called shallow copy.
Ex:-
Public class TestClass
{
int x;
}
TestClass obj1=new TestClass(){x=1};
TestClass obj2=obj1;
//Print(obj1.x)
//prints 1
//Print(obj2.x)
//prints 1

obj1.x=4 ;
//Print(obj1.x)
//prints 4
//Print(obj2.x)
//prints 4

Incase of Deep copy, the reference pointers are not expected to be copied instead will create a new memory block and copy the contents of the object.
The pointer of the new reference will point to the new object which is created.

To make the same above given example to do deep copy it can done either by making “TestClass” to implement “ICloneable” or like below.
Ex:-
Public class TestClass
{
int x;
}
TestClass obj1=new
TestClass(){x=1};
TestClass obj2=new TestClass(){x=obj1.x};
//Print(obj1.x)
//prints 1
//Print(obj2.x)
//prints 1

obj1.x=4 ;
//Print(obj1.x)
//prints 4
//Print(obj2.x)
//prints 1

Or by Implementing ICloneble

public class TestClass : ICloneable
{
int x;
public object Clone()
{
return new TestClass() { x = this.x };
}
}

No comments:

Post a Comment