I know there's tons of question on the matter. But I couldn't, for the life of me, make any sense of the answers or use them in my example. I am newish in vb .net and I can't really implement general examples to my specific one. What I have is basically this:
dim a as New list(of player)
EDIT: dim b as New list(of player) 'previously was: dim b as new player
Class player
Public name As String
'[more]
End Class
[....]
a.Add(New player)
b.Add(New player)
a(0).name="john"
b=a
a(0).name="jack"
msgbox(b(0).name) 'it will print jack instead of john
I now this can be done with ICloneable, but after reading up a lot on it I can't implement correctly. Thank you in advance
When you assign
a(0)tobthey are both pointing to the same object in memory. Even though you declaredbasNew playerthat new player was thrown away when you made the assignment to an existing player.To prove this to yourself, try the opposite. Change the
nameproperty ofband you will see it is reflected in thenameproperty ofa(0).Now to Clone...
Your class now implements
ICloneablewith the addition of theClonefunction. You can implement this however you wish as long as the signature of the function matches the interface signature for theClonemethod.Notice that my implementation is creating a
Newplayer and is assigning thenameproperty to thenameof the existing player. This New player is what is returned by the function. The New player will have a different location in memory so changes to the first player from the list and this new player will not affect each other.Since the
Clonefunction returns an object, we need to cast it toplayer(the underlying type) so it will match our declare ofband we will be able to use the properties and methods of theplayerclass.EDIT
To accomplish your goal using 2 lists, I created a new class called
PlayerList. It inheritsList(Of Player)and implementsICloneable. You can now clone listaand get completely separate lists with composed of separate player objects.