I would like to confirm the expanation to some things I've been trying to understand.
I have two scenarios:
Scenario 1: I have one list stored in a private field of my class, I make a deep copy of it and store it in other private field. After doing so, I make some changes in the list, but I can choose to retrieve its original state. For doing so, I assign the copy of the original listto the modified one:
Public Class ClassX
Private myList As List(Of Double)
Private myOriginalList As List(Of Double)
Public Sub New()
myList = New List(Of Double)
myOriginalList = ObjectCopier.Clone(myList)
End Sub
Private Sub Main()
ChangeMyList()
'myList has one element
RevertChanges()
'myList has zero elements
End Sub
Public Sub ChangeMyList()
Dim r As New Random
myList.Add(r.NextDouble)
End Sub
Public Sub RevertChanges()
myList = myOriginalList
End Sub
End Class
Doing so, makes everything work as I would expect.
Scenario 2: The idea is pretty much the same, make a deep copy of one list for allowing the retrieval of its original state. However, in this case, the list is passed to another object, which makes a deep copy of it, modifies it, and decides to save those changes or revert them. And by doing so, I cannot get the desired behaviour, since the list is changed even when I make the assignment "myList = myOriginalList". Code:
Public Class ClassX
Private myList As List(Of Double)
Private Sub Main()
Dim myList As New List(Of Double)
Dim c As New ClassY(myList)
c.ChangeList()
'myList has one element
c.RevertChanges()
'myList still has one element
End Sub
End Class
Public Class ClassY
Private myList As List(Of Double)
Private myOriginalList As List(Of Double)
Public Sub New(ByVal c As List(Of Double))
myList = c
myOriginalList = ObjectCopier.Clone(myList)
End Sub
Public Sub ChangeList()
Dim r As New Random
myList.Add(r.NextDouble)
End Sub
Public Sub RevertChanges()
myList = myOriginalList
End Sub
End Class
So the question is... why? Why can I revert changes this way in the first case, but not in the second? Why changes made to the list passed as reference to ClassY are saved, but an assignment is not transmited to the original list in ClassX?
Hope it makes sense! Thanks!