Shared 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.
Example. 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.
Step 1 We access the Shared gems Dictionary and add 2 keys with values to it. To access a shared field, we must use the full class name.
Step 2 We call a Shared Function that can access the Dictionary, and its uses GetValueOrDefault to access a value from the Dictionary.
Step 3 We call a Function that uses a 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]
Summary. Shared Dictionaries can both reduce memory usage, by eliminating duplicate fields, and simplify programs, by allowing us to unify the Dictionary initialization logic.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.