Copying an Object

mattkw80

Well-known member
Joined
Jan 3, 2008
Messages
49
Location
Ontario, Canada
Programming Experience
Beginner
Sorry, still pretty new bear with me...

I have a Class called People.

I have an object called Roger, another called Sally.

How can I copy my 'Roger' object over top of 'Sally' so they are identical?
 

newguy

Well-known member
Joined
Jun 30, 2008
Messages
611
Location
Denver Co, USA
Programming Experience
1-3
VB.NET:
Public Class People
'stuff...
End Class

'in a form far far away
Dim roger As New People
Dim sally As New People
sally = roger
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,431
Location
Norway
Programming Experience
10+
That will not create a copy, it will simply reference the sally variable to point to the same object as roger variable. Try this to see what result you get:
VB.NET:
Dim same As Boolean = sally Is roger
To provide cloning you have to write code to do that yourself (ie create object and copy the data), the standarized way to do this is to have your class implement ICloneable Interface (System) and perform your actions in the Clone method, here the simplest solution is to use the protected Object.MemberwiseClone Method (System) that all object have inherently. Here is a sample Person class that is clonable (shallow):
VB.NET:
Public Class Person
    Implements ICloneable

    Private _name As String
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

    Public Function Clone() As Object Implements System.ICloneable.Clone
        Return Me.MemberwiseClone
    End Function
End Class
Example usage:
VB.NET:
Dim p1 As New Person
p1.Name = "Sally"
Dim p2 As Person = CType(p1.Clone, Person)
See what Name the Person object in p2 variable has. Also now try this:
VB.NET:
Dim same As Boolean = p1 Is p2
If you didn't catch the "same" point; two different object instances are not the same. When you create copy of an object (clone) you have a new object that is not the same as the original, even if it contains the same data.
 

newguy

Well-known member
Joined
Jun 30, 2008
Messages
611
Location
Denver Co, USA
Programming Experience
1-3
It sounded like he wanted to change the object(sally) to be the same as object(roger).
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,431
Location
Norway
Programming Experience
10+
That could be, but the terminology would be wrong. Pointing two variables to same object does not make a copy of the object, only a copy of the reference.
 

newguy

Well-known member
Joined
Jun 30, 2008
Messages
611
Location
Denver Co, USA
Programming Experience
1-3
It's just how I read the last line in the OP's last statement in post #1. I totally agree with your statement for making a copy, I think we are on diff page as far as interpreting the question - LOL.
 
Top Bottom