Background
With the advent of the .NET Framework, Visual Basic received a type-safe and efficient data structure for storing key-value pairs — Dictionary(Of TKey, TValue). This is a standard associative container for quick lookups.
Problem
Working with a dictionary often causes errors: trying to access a value via a key that does not exist leads to an exception. Operations for adding, changing, and adding new values are often confused as well.
Solution
To access values, use the indexer or methods TryGetValue, ContainsKey. To avoid the KeyNotFoundException, always perform an explicit check:
Code example:
Dim dict As New Dictionary(Of String, Integer)() dict.Add("one", 1) dict("two") = 2 ' Adding a new pair If dict.ContainsKey("three") Then Console.WriteLine(dict("three")) ' Will not throw an error Else Console.WriteLine("Key not found") End If Dim value As Integer = 0 If dict.TryGetValue("one", value) Then Console.WriteLine(value) End If
Key features:
Is it true that dict("key") always adds a new key-value pair?
No. If the key exists, the value is updated. If it does not exist, the pair is added. To add with an error if the key exists — use Add.
Will TryGetValue throw an exception if the key is not present?
No. It will return False without throwing an exception and will not change the value. This is a safe way to access.
Can you store value types (e.g., Integer) as TValue in Dictionary and still get null for a missing key?
No. For value types the default value for the type is returned (0 for Integer), but accessing via the indexer will still throw an exception if the key is missing.
Accessing the dictionary by index without prior check is duplicated in different places — causing periodic crashes of the program.
Pros:
Cons:
Widespread use of TryGetValue, all accesses are protected, cases of missing keys are logically handled.
Pros:
Cons: