Hopefully this is simple enough. I need to be able to add elements to a copy of mylist.testlist without modifying the global mylist object. (Which seems to be happening via the below code.)
When I am working on x, which should be a totally separate object, mylist is getting modified as well. How can I fix this? I have worked with lists extensively and never seen this behavior before. I have tested and reproduced the problem in .NET 3.5 and .NET 4.0 on Win 7 Pro 32bit.
TIA!
Source Code:
Public Class Form1
Public mylist As New test
Sub Main()
Dim x As test = mylist
For i As Integer = 0 To 10
x.testlist.Add(False)
Next
MsgBox("x count: " + x.testlist.Count.ToString + vbCrLf + "mylist count: " + mylist.testlist.Count.ToString)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Main()
End Sub
End Class
Public Class test
Public testlist As New List(Of Boolean)
Public Sub New()
testlist.Add(False)
End Sub
End Class
As Tim Schmelter pointed out in his comment, your problem is the line:
by which
xgets a reference tomylist. That means both (xandmylist) are pointing to the same instance oftest. That’s why changing one of them is changing the other too.To fix it, you could define
xas a new instance oftestand copy all elements frommylist.testlisttox.testlist.