Home
VB.NET
Dictionary GetValueOrDefault Example
This page was last reviewed on Oct 25, 2023.
Dot Net Perls
GetValueOrDefault. Many VB.NET programs use the Dictionary type, and accessing values is nearly always needed. The GetValueOrDefault function provides an easy and safe way to do this.
Dictionary
Dictionary TryGetValue
With this function, we get the default value (not an error) if the key is not found. This often allows to us omit If-checks in our programs, making them clearer.
Example. It is important to understand the use of the GetValueOrDefault function a complete VB.NET program. We must first create a Dictionary to test this function.
Part 1 We create a Dictionary and populate it with 2 keys and values. We have String keys, and Integer values.
Part 2 We invoke GetValueOrDefault on a key that exists. The correct value (10) is returned.
Part 3 When the key is not found, a default value is returned. For an Integer value, the default is 0.
Module Module1 Sub Main() ' Part 1: create Dictionary. Dim animals As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer) animals.Add("cat", 10) animals.Add("dog", 20) ' Part 2: use GetValueOrDefault. Dim result = animals.GetValueOrDefault("cat") Console.WriteLine($"cat = {result}") ' Part 3: key not found. result = animals.GetValueOrDefault("computer") Console.WriteLine($"computer = {result}") End Sub End Module
cat = 10 computer = 0
String values. What happens when we use GetValueOrDefault on a Dictionary with String values? In VB.NET the default value for a String is Nothing.
Nothing
Part 1 We create a Dictionary, and we leave it empty because we are just testing nonexistent values in this program.
Part 2 We access a key that is not present. This means no valid String can be returned.
Part 3 To test the return value of GetValueOrDefault for no String value, we can use the IsNothing function.
Warning Testing against the Nothing constant does not work correctly—it is best to always use IsNothing.
Module Module1 Sub Main() ' Part 1: create an empty Dictionary with string values. Dim ids = New Dictionary(Of String, String) ' Part 2: get key that is not found. Dim result = ids.GetValueOrDefault("missing") ' Part 3: we can test for Nothing with IsNothing. If IsNothing(result) Console.WriteLine("OK") End If End Sub End Module
OK
Summary. A simple function that makes Dictionary collections easier to use is worth knowing about. GetValueOrDefault can replace many uses of TryGetValue and the indexer.
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.
This page was last updated on Oct 25, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.