I have tried to simplify and annotate the code which is giving me a headache below. It demonstrates my problem. Simply put, I have two separate stacks and I am trying to pop from one stack. For some reason, when you pop one of the stacks, it actually seems to pop the other one as well?! Is this by design and if so, why and how should I work around it?
… or am I just being a muppet? (don’t answer that one)
Public Class Form1
Public _stackMaster As New Stack
Public _stackCopy As New Stack
Public _strPopped As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
_stackMaster.Push("line1")
_stackMaster.Push("line2")
_stackMaster.Push("line3")
MsgBox("Before copying the Master stack to the Copy stack." & vbCrLf & "_stackMaster.Count=" & _stackMaster.Count & vbCrLf & "_stackCopy.Count=" & _stackCopy.Count)
_stackCopy = _stackMaster
MsgBox("After copying the Master stack to the Copy stack." & vbCrLf & "_stackMaster.Count=" & _stackMaster.Count & vbCrLf & "_stackCopy.Count=" & _stackCopy.Count)
_strPopped = _stackCopy.Pop
MsgBox("After popping a string from the Copy stack." & vbCrLf & "_stackMaster.Count=" & _stackMaster.Count & vbCrLf & "_stackCopy.Count=" & _stackCopy.Count & vbCrLf & "Why do both counts decrease?? Aren't they separate stacks?")
End
End Sub
End Class
This line is your culprit.
_stackCopyand_stackMasterare each references to stack instances. When you assign one to the other, you are making them each reference the same instance. What you want to do is Clone_stackMasterand assign THAT to_stackCopy.