Reputation: 373
I am trying to create a Dictionary collection of keys, where each key would have a corresponding value of class "look".
The following example does not work. It gives me:
first - circle, blue
second - circle, blue
While I need:
first - square, red
second - circle, blue
Why does it not work and how can I make it work?
Thank you.
Public Class Form1
Public Class look
Public shape As String
Public color As String
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myDict As New Dictionary(Of String, look)
Dim oLook As New look
oLook.shape = "square"
oLook.color = "red"
myDict.Add("first", oLook)
oLook.shape = "circle"
oLook.color = "blue"
myDict.Add("second", oLook)
For Each key In myDict.Keys
MsgBox(key & " - " & myDict(key).shape & ", " & myDict(key).color)
Next
End Sub
End Class
Upvotes: 1
Views: 3827
Reputation: 885
Try this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myDict As New Dictionary(Of String, look)
Dim oLook As New look
oLook.shape = "square"
oLook.color = "red"
myDict.Add("first", oLook)
oLook = new look ' This will create another oLook object and point olook at it.
oLook.shape = "circle"
oLook.color = "blue"
myDict.Add("second", oLook)
For Each key In myDict.Keys
MsgBox(key & " - " & myDict(key).shape & ", " & myDict(key).color)
Next
End Sub
Upvotes: 3
Reputation: 2297
You need a new instance of the class:
Dim myDict As New Dictionary(Of String, look)
Dim oLook As New look
oLook.shape = "square"
oLook.color = "red"
myDict.Add("first", oLook)
oLook = New look '<<<<<<<<<<<<
oLook.shape = "circle"
oLook.color = "blue"
myDict.Add("second", oLook)
For Each key In myDict.Keys
MsgBox(key & " - " & myDict(key).shape & ", " & myDict(key).color)
Next
Upvotes: 2