ProgrammingBackend Developer (Visual Basic)

How to implement dictionaries (Dictionary(Of TKey, TValue)) in Visual Basic, what operations are available, what pitfalls are there when accessing values by a non-existent key?

Pass interviews with Hintsage AI assistant

Answer.

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:

  • Fast key access (hashing)
  • Explicit key presence check prevents errors
  • Removing and replacing values by key is implemented via Remove and the indexer

Trick questions.

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.

Typical mistakes and anti-patterns

  • Accessing a non-existent key via indexer without check
  • Duplicating keys via Add (causes ArgumentException)
  • Ignoring TryGetValue's return value

Real-life example

Negative case

Accessing the dictionary by index without prior check is duplicated in different places — causing periodic crashes of the program.

Pros:

  • Compact code

Cons:

  • Application instability, hard to catch errors

Positive case

Widespread use of TryGetValue, all accesses are protected, cases of missing keys are logically handled.

Pros:

  • Stable behavior, no exceptions

Cons:

  • Need to introduce out variables for values