Best way to assign one class to another

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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
 
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

What you just did will work.

This would work if you want to clone it:
myClass2 = (MyClass)myClass1.Clone();
 
Hi,


Eitan said:
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 ;

You have to clarify what you want, in the above code you still have two
instances and they will contain different values, but now you have both
myClass2 and myClass1 referencing to the same instance.
If what you want is making both instances to hold the same values you could
create a method to "copy" the values from one to the other. Of course this
can be more complex like what happen in the case that one member is a
reference type. Do you want to create another instance of it? or just copy
the current one?

Google for "shallow copy" , "deep copy" and take a look at the IClone
interface.
 
Back
Top