VB.NET TryGetValue Example

The VB.NET programming language

Frequently, when you want to access a value through a key in a Dictionary collection, you want to use logic that acts upon the value. The TryGetValue function in VB.NET, then, combines the lookup step with the value-returning step. The TryGetValue function enables important optimizations in VB.NET programs.

These VB example programs use the TryGetValue Function on the Dictionary type.

Example

As we begin, please notice that the Dictionary instance is created with a String key and an Integer value. Next, a dummy key is added that will be used in the following steps. In the slow version of the code, the ContainsKey is called, and then the Dictionary value is incremented.

This version is slow because three lookups must be performed: two to load the value, and one to store the new value. The fast version follows: it only requires two lookups because the initial lookup returns the value and we simply reuse that.

Program that uses TryGetValue function [VB.NET]

Module Module1
    Sub Main()
	' Create a new Dictionary instance.
	Dim dict As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)
	dict.Add("key", 0)

	' Slow version: use ContainsKey and then increment at a key.
	If (dict.ContainsKey("key")) Then
	    dict("key") += 1
	End If

	' Fast version: use TryGetValue and only do two lookups.
	Dim value As Integer
	If (dict.TryGetValue("key", value)) Then
	    dict("key") = value + 1
	End If

	'Output.
	Console.WriteLine(dict("key"))
    End Sub
End Module

Output

2
Performance optimization

Performance optimization with TryGetValue. TryGetValue, then, can be used as a performance optimization in many algorithms by reducing the number of lookups on the Dictionary collection. Please remember that Dictionary lookups are often not a big bottleneck in programs, but every performance optimization can help.

Summary

As a speed optimization, the TryGetValue introduces a second parameter to the lookup function, one that stores the value if one was found. TryGetValue doubles as a lookup method and also a method that returns the actual value. It is critical to optimal use of the Dictionary type.

Dictionary Examples VB.NET Tutorials
.NET