Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a "clone" of this object, not point to it

Let's say I got a list called

myFirstList

And then I want to create a copy of that list so I can do some tweaks of my own. So I do this:

mySecondList = myFirstList
mySecondList.doTweaks

But I noticed that the tweaks also affect the myFirstList object! I only want the tweaks to affect the second one...

And afterwards I will want to completely delete mySecondList, so I do mySecondList = Nothing and I'm good, right?

like image 585
Voldemort Avatar asked Apr 06 '11 23:04

Voldemort


2 Answers

Expanding on Adam Rackies' answer I was able to implement the following code using VB.NET.

My goal was to copy a list of objects that served mainly as data transfer objects (i.e. database data). The first the class dtoNamedClass is defined and ShallowCopy method is added. A new variable named dtoNamedClassCloneVar is created and a LINQ select query is used to copy the object variable dtoNamedClassVar.

I was able to make changes to dtoNamedClassCloneVar without affecting dtoNamedClassVar.

Public Class dtoNamedClass


    ... Custom dto Property Definitions



  Public Function ShallowCopy() As dtoNamedClass
    Return DirectCast(Me.MemberwiseClone(), dtoNamedClass)
  End Function

End Class


Dim dtoNamedClassVar As List(Of dtoNamedClass) = {get your database data}

Dim dtoNamedClassCloneVar = 
    (From d In Me.dtoNamedClass
        Where {add clause if necessary}
        Select d.ShallowCopy()).ToList
like image 59
wavedrop Avatar answered Sep 20 '22 06:09

wavedrop


Adam Rackis, I don't like your "Of course it does", because it is not at all obvious.

If you have a string variable that you assign to another string variabe, you do not change them both when making changes to one of them. They do not point to the same physical piece of memory, so why is it obvious that classes do?

Also, the thing is not even consistent. In the following case, you will have all elements in the array pointing at the same object (they all end up with the variable Number set to 10:

SourceObject = New SomeClass
For i = 1 To 10
   SourceObject.Number = i
   ObjectArray.Add = SourceObject   
Next i

BUT, the following will give you 10 different instances:

For i = 1 To 10
   SourceObject = New SomeClass
   SourceObject.Number = i
   ObjectArray.Add = SourceObject   
Next i

Apparently the scope of the object makes a difference, so it is not at all obvious what happens.

like image 34
FrankB Avatar answered Sep 20 '22 06:09

FrankB