TryAdd. Sometimes in a VB.NET program we want to add only keys to a Dictionary that are not yet present. With TryAdd, we add only new keys, and a Boolean is returned.
The return value tells us whether the key was added. TryAdd can replace uses of the indexer and the Add() function, and results in clearer code.
Example. As we begin please notice that the Dictionary has String keys and Integer values, although this is not important. String keys are common in VB.NET programs.
Step 1 We create a Dictionary, and with the Add() function we insert 2 keys and 2 values into it.
Step 2 We use TryAdd with an argument that is a key already present in the Dictionary. TryAdd returns False, and nothing changes.
Step 3 When a key is used that does not exist yet, it is added in the same way that the Add() function would work.
Module Module1
Sub Main()
' Step 1: create a dictionary.
Dim birds = New Dictionary(Of String, Integer)
birds.Add("parrot", 1)
birds.Add("sparrow", 1)
' Step 2: use TryAdd on existing key.
If birds.TryAdd("parrot", 2)
' Not reached.
Else
Console.WriteLine("Parrot already exists; not adding")
End if
' Step 3: add a bird that does not exist.
If birds.TryAdd("vulture", 2)
Console.WriteLine("Added new bird")
Else
' Not reached.
End If
End Sub
End ModuleParrot already exists; not adding
Added new bird
Indexer versus TryAdd. The indexer assignment in VB.NET will replace an existing value at a key. The TryAdd() function, meanwhile, will not do this.
Part 1 We create a Dictionary and with Add() we insert 1 key. The value of "blue" starts off at 10.
Part 2 We use the indexer to change the value at "blue" to 20. The program prints 20.
Part 3 We use TryAdd, but since "blue" already exists, nothing is changed in the Dictionary. The value for "blue" is still 20.
Module Module1
Sub Main()
' Part 1: create a dictionary, and add one key.
Dim colors = New Dictionary(Of String, Integer)
colors.Add("blue", 10)
Console.WriteLine(colors.GetValueOrDefault("blue"))
' Part 2: replace value at this key with indexer assignment.
colors("blue") = 20
Console.WriteLine(colors.GetValueOrDefault("blue"))
' Part 3: use TryAdd on the same key, which does not update the value.
colors.TryAdd("blue", 30)
Console.WriteLine(colors.GetValueOrDefault("blue"))
End Sub
End Module10
20
20
Summary. The TryAdd() Function in VB.NET can make many programs that use Dictionary clearer and easier to reason about. And it can reduce the amount of code we have to write.
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.