Sunday, November 23, 2008

Copy Collections in VB.Net

I learned today that collB = CollA only copies a reference and not the values in the collection. If you try to view data for collB.Item(2) it will show the same value as CollA.ITem(2), but if you later run CollA.Clear() then CollB is cleared as well. To make a copy of a collection you have to copy it item by item instead. See code below for a demonstration.

Code: (Add a button to a form to run code)
Public Class Form1
Dim aa As New Collection
Dim bb As New Collection
Dim cc As New Collection

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
aa.Add("burkA")
aa.Add("burkB")
aa.Add("burkC")

bb = aa
MsgBox("This is collection aa(2) " + aa.Item(2).ToString)
MsgBox("This is collection bb(2) " + bb.Item(2).ToString)

For Each c As String In aa
cc.Add(c)
Next

aa.Clear()
Try
MsgBox(bb.Item(2).ToString)
Catch ex As Exception
MsgBox("CollectionData bb(2)isn't anymore")
End Try
Try
MsgBox("This is collection cc(2) " + cc.Item(2).ToString)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class

No comments:

MySQL to MariaDB

 Here is a good description how to migrate to MariaDb MySQL to MariaDb Example of how to dump data from MySQL port=3307: mysqldump --user=ro...