Shared Dictionary Example
This page was last reviewed on Jan 9, 2024.
Dot Net Perls
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.
Dictionary GetValueOrDefault
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 Module
SHARED 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 9, 2024 (new).
© 2007-2024 Sam Allen.