Thierry Savard Saucier
Thierry Savard Saucier

Reputation: 449

Duplicate a class instance

Soo, I have a combo box who have as datasource a list of custom object (the "Person" class). I have mapped the Person.Name to be the DisplayMember, and the object is the value selected.

when someone select a "Bob" person and press on ChoosePerson, I want to take this person, duplicate it, and use the duplicata to do stuff.

Heres the code to explain it :

 Private Sub ChoosePerson_Click(sender As Object, e As EventArgs) Handles ChoosePerson.Click
    Dim p As Person= CType(cbPerson.SelectedValue, Person)
    MyChosenList.Add(ChoseAPerson(m))
    cbPerson.SelectedIndex() = 0
End Sub

Private function ChoseAPerson(byval p as Person) as Person
   Dim newPerson as Person = p 
   newPerson.name = "ANewPerson_"  & p.Name
   Return newPerson
End function

Now, if I go back to my combo box cbPerson, the person I selected earlier (bob) will have its name replace for "ANewPerson_bob"

how can I make sure that the "bob" person I add to myChosenList is a different instance of Person class ?

EDIT

I add to scout a little on google to find the right way to do a clone of my object as @dotNET suggested it

Public Function Clone() As Object Implements ICloneable.Clone
    Return DirectCast(MemberwiseClone(), Person)
End Function

Upvotes: 0

Views: 1402

Answers (2)

dotNET
dotNET

Reputation: 35400

The standard way to solve this problem is to implement IClonable and then Clone() method to create a copy of your object. Then in your code, write this:

Dim p As Person= CType(cbPerson.SelectedValue, Person).Clone()

The basic problem is that Persons is a class, and is therefore copied by reference and not by value. Creating a new reference still points to the same physical object.

Upvotes: 2

nhgrif
nhgrif

Reputation: 62052

Rather than doing this:

Dim newPerson as Person = p 

You need to write a copy constructor for Person, and do this:

Dim newPerson as New Person(p)

Upvotes: 0

Related Questions