Home
VB.NET
Dictionary TryGetValue Example
Updated Oct 26, 2023
Dot Net Perls
TryGetValue. In VB.NET programs there are many ways to access values based on keys in a Dictionary. But TryGetValue is one of the safest and most effective.
Dictionary
With this function, we receive a value only if the key exists. It returns a Boolean telling us whether the key exists. TryGetValue is often used in an If.
Boolean
If
Example. For showing the usage of TryGetValue, we must first have a Dictionary. The program creates a Dictionary and populates it as we begin.
Part 1 We use TryGetValue on a key that exists in the colors Dictionary. The "test" variable is assigned to 50.
Part 2 We can use TryGetValue without an If. The result variable will be left with its initial value if no key is found.
Part 3 If the key is not found, TryGetValue returns False. In some programs, knowing a key is missing is helpful.
Module Module1 Sub Main() Dim colors = New Dictionary(Of String, Integer) colors.Add("red", 50) colors.Add("orange", 51) ' Part 1: use TryGetValue to get an existing value. Dim test = 0 If colors.TryGetValue("red", test) Console.WriteLine(test) End If ' Part 2: use TryGetValue without If. Dim test2 = 0 colors.TryGetValue("orange", test2) Console.WriteLine(test2) ' Part 3: use TryGetValue when no key exists. Dim test3 = 0 If colors.TryGetValue("cat", test3) ' Not reached. Else Console.WriteLine("Cat not found!") End If End Sub End Module
50 51 Cat not found!
GetValueOrDefault. Another function that can perform a similar task to TryGetValue is GetValueOrDefault. In a sense, GetValueOrDefault is like TryGetValue without an If-statement.
Dictionary GetValueOrDefault
Part 1 We use TryGetValue on a key that does not exist in the Dictionary, and the result is left with its initial value 0.
Part 2 We use GetValueOrDefault, and the default value for Integer is returned, which is also the value 0.
Module Module1 Sub Main() Dim sizes = New Dictionary(Of Char, Integer) sizes.Add("s", 1) sizes.Add("m", 2) sizes.Add("l", 3) ' Part 1: use TryGetValue. Dim result1 = 0 sizes.TryGetValue("z", result1) Console.WriteLine(result1) ' Part 2: use GetValueOrDefault. Dim result2 = sizes.GetValueOrDefault("z") Console.WriteLine(result2) End Sub End Module
0 0
Summary. Accessing keys to look up values in a Dictionary is frequently done in VB.NET programs. With TryGetValue and its companion function GetValueOrDefault, this is done safely.
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.
This page was last updated on Oct 26, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen