Make the value of MyObjectA equal to the value of MyObjectB?

  • Thread starter Thread starter Bruce
  • Start date Start date
B

Bruce

I am a C++ programmer so sorry for the simple VB question.

If I have two instances of the same type of object, how do I make the
value of one equal to the other?

If I do

Dim ObjA as new MyObject
Dim ObjB as new MyObject

ObjA = ObjB


then ObjA is set to the same instance as ObjB.

How do I just make the values equal? Do I need a CopyTo method for the
object?
 
If all the members of MyObject are value types then you can use:

ObjA = ObjB.Clone()

If any of the members are reference types then you needs to handle them in
some other way.

Either way the two instances will not be equal, even though they may have
the same content.
 
Stephany said:
If all the members of MyObject are value types then you can use:

ObjA = ObjB.Clone()

If any of the members are reference types then you needs to handle them in
some other way.

Either way the two instances will not be equal, even though they may have
the same content.


Thanks for the quick reply.

Some members are other objects. I would assume that MyObject would have
to implement the Clone method? Actually I am trying to picture what
such a method would look like.
 
Public Class MyObject
Implements ICloneable

....
....
....
....

Public Function Clone() As MyObject Implements ICloneable.Clone

Dim _clone as New MyObject

'Do the stuff here to populate the members of _clone from Me

'If member X is a value type or a System.String then it is simply
_clone.X = Me.X

'If member Y is a reference type and is not a System.String then
'you need to ensure that you get a copy and not a reference

'The reason that _clone.X = Me.X works for a System.String is that
'a System.String is immutable so you get a new copy of it instead
'of a reference

'When all the cloning is done simply
Return _clone

End Function

End Class
 
Stephany said:
Public Class MyObject
Implements ICloneable

....
....
....
....

Public Function Clone() As MyObject Implements ICloneable.Clone

Dim _clone as New MyObject

'Do the stuff here to populate the members of _clone from Me

'If member X is a value type or a System.String then it is simply
_clone.X = Me.X

'If member Y is a reference type and is not a System.String then
'you need to ensure that you get a copy and not a reference

'The reason that _clone.X = Me.X works for a System.String is that
'a System.String is immutable so you get a new copy of it instead
'of a reference

'When all the cloning is done simply
Return _clone

End Function

End Class


Thanks again Stephany.

It is much more clear now. Clone is very similar to a factory.
 
Back
Top