Void Star
Void Star

Reputation: 2521

Use Visual Basic dictionary with strings

I have a dictionary object in Visual Basic which I want to access with string keys. The problem is, Visual Basic is storing references to strings, rather than the strings themselves. So when I index the dictionary with a key, it always fails because the object references are not equal. What is the point of a dictionary I cannot index? How do I solve this?

Edit:

To be more clear, I want to be able to use this more like a Python dictionary, where string keys are immutable types and therefore the contents rather than the object references are compared.

Upvotes: 0

Views: 725

Answers (1)

decyclone
decyclone

Reputation: 30840

Strings in .Net ARE immutable. And Dictionary DOES work as you want it to work:

Dim Store As New Dictionary(Of String, Object)

Store("Key1") = New Form()
Store("Key2") = New Exception()
Store("Key3") = 10
Store("Key4") = "Test"

MessageBox.Show(Store("Key1").GetType().FullName) ' System.Windows.Forms.Form
MessageBox.Show(Store("Key2").GetType().FullName) ' System.Exception
MessageBox.Show(Store("Key3").GetType().FullName) ' System.Int32
MessageBox.Show(Store("Key4").GetType().FullName) ' System.String

Upvotes: 3

Related Questions