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.
Dim colors = New Dictionary(Of String, Integer)
' Part 1: use TryGetValue to get an existing value.
Dim test = 0
If colors.TryGetValue("red", test)
' Part 2: use TryGetValue without If.
Dim test2 = 0
' Part 3: use TryGetValue when no key exists.
Dim test3 = 0
If colors.TryGetValue("cat", test3)
' Not reached.
Console.WriteLine("Cat not found!")
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.
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.
Dim sizes = New Dictionary(Of Char, Integer)
' Part 1: use TryGetValue.
Dim result1 = 0
' Part 2: use GetValueOrDefault.
Dim result2 = sizes.GetValueOrDefault("z")
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 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.