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.
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.
Dictionary
, and with the Add()
function we insert 2 keys and 2 values into it.TryAdd
with an argument that is a key already present in the Dictionary
. TryAdd
returns False, and nothing changes.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
TryAdd
The indexer assignment in VB.NET will replace an existing value at a key. The TryAdd()
function, meanwhile, will not do this.
Dictionary
and with Add()
we insert 1 key. The value of "blue" starts off at 10.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
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.