all groups > dotnet academic > july 2007 >
You're in the

dotnet academic

group:

Coping one Object to another......


Coping one Object to another...... Eitan
7/2/2007 1:34:00 PM
dotnet academic:
Hello,

Suppose I have created 2 objects of MyClass:

MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass();

I also defined variables inside MyClass1:

myClass1.myVar1 = 1 ;
myClass1.myVar2 = 2 ;

What would be the best, elegant, way to achive:

myClass2 = myClass1 ;

Thanks
Eitan
Re: Coping one Object to another...... PvdG42
7/2/2007 5:08:57 PM

[quoted text, click to view]
Assuming C#.
You need to understand that objects are reference types that hold the
address of the actual object. So, a statement like

myClass2 = myClass1 ;

simply assigns the memory address in myClass1 to myClass2, making myClass2 a
second reference to the same object.
In order to make a second object that is a clone of myClass1 you must do a
member-wise copy of the field values in the object referenced by myClass1
into the same fields in the object referenced by myClass2.
One way this is frequently accomplished is by including a copy constructor
in your class definition.
Re: Coping one Object to another...... Eitan
7/3/2007 7:00:05 AM
Thanks
Eitan

[quoted text, click to view]
AddThis Social Bookmark Button