The Dictionary in Visual Basic is an associative collection that allows you to store key-value pairs. In VB.NET, it uses Dictionary(Of TKey, TValue) from the System.Collections.Generic namespace.
Early versions of Visual Basic were limited to classical collections (Collection), which only supported string or numeric keys without typing. With the emergence of VB.NET and the .NET Framework, the generic Dictionary was introduced, making the work with associative data safer and faster.
Common mistakes when using Dictionary include:
When working with Dictionary, it is critically important to:
ContainsKey methodCode example:
Dim dict As New Dictionary(Of String, Integer) dict("apples") = 10 ' Safe check before accessing: If dict.ContainsKey("bananas") Then Console.WriteLine(dict("bananas")) Else Console.WriteLine("Key not found!") End If
Key features:
What exception is thrown when attempting to access a non-existent key in Dictionary and how to avoid it?
Error: System.Collections.Generic.KeyNotFoundException. You need to use the ContainsKey method to prevent this error.
Can you change the keys of already existing elements in a Dictionary?
No. A key cannot be changed after it has been added—you can only remove the element and add a new one with a different key.
What distinguishes Dictionary from Hashtable in VB.NET?
Dictionary is type-safe (generic), works faster, and does not require boxing/unboxing of values. Hashtable is outdated and not recommended for use.
** Negative case
A programmer saves sales statistics by cities via Dictionary but does not check if the city key exists in the collection before accessing it. They receive a KeyNotFoundException when reporting on a new city.
Pros:
Cons:
** Positive case
The same report, but when accessing a key, ContainsKey check is always used, and if the key is missing, it returns 0 or outputs a message.
Pros:
Cons: