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.
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.
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.
Dictionary
and populate it with 2 keys and values. We have String
keys, and Integer values.GetValueOrDefault
on a key that exists. The correct value (10) is returned.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 Modulecat = 10 computer = 0
String
valuesWhat happens when we use GetValueOrDefault
on a Dictionary
with String
values? In VB.NET the default value for a String
is Nothing.
Dictionary
, and we leave it empty because we are just testing nonexistent values in this program.String
can be returned.GetValueOrDefault
for no String
value, we can use the IsNothing
function.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 ModuleOK
A simple function that makes Dictionary
collections easier to use is worth knowing about. GetValueOrDefault
can replace many uses of TryGetValue
and the indexer.