Dictionary
Suppose we have some data that is useful throughout our VB.NET program, not just one class
. And it can be stored within a Dictionary
—a Shared Dictionary
is ideal here.
With this construct, we can designate a Dictionary
as a global store of key-value pairs. We can add, loop over, test and remove keys from the Shared Dictionary
.
We introduce a class
named Example, and inside the Example class
we have a Shared Dictionary
"gems." This Dictionary
stores String
keys and Integer values among all Example instances.
Dictionary
and add 2 keys with values to it. To access a shared field, we must use the full class
name.Dictionary
, and its uses GetValueOrDefault
to access a value from the Dictionary
.For-Each
loop on the Shared Dictionary
, and it prints all pairs.Class Example Public Shared Dim gems As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer) Shared Sub Test() ' Use GetValueOrDefault to find a value. Dim value As Integer = gems.GetValueOrDefault("diamond") Console.WriteLine($"SHARED DICTIONARY RESULT: {value}") End Sub Shared Sub PrintAll() ' Use For-Each loop to enumerate entries in the Dictionary. For Each pair in gems Console.WriteLine($"PAIR: {pair}") Next End Sub End Class Module Module1 Sub Main() ' Step 1: add 2 entries to the Shared Dictionary. Example.gems.Add("diamond", 500) Example.gems.Add("ruby", 200) ' Step 2: find a value for a key on the Shared Dictionary. Example.Test() ' Step 3: print all entries in the Shared Dictionary. Example.PrintAll() End Sub End ModuleSHARED DICTIONARY RESULT: 500 PAIR: [diamond, 500] PAIR: [ruby, 200]
Shared Dictionaries can both reduce memory usage, by eliminating duplicate fields, and simplify programs, by allowing us to unify the Dictionary
initialization logic.