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.
' Step 1: create a dictionary.
Dim birds = New Dictionary(Of String, Integer)
' Step 2: use TryAdd on existing key.
If birds.TryAdd("parrot", 2)
' Not reached.
Console.WriteLine("Parrot already exists; not adding")
' Step 3: add a bird that does not exist.
If birds.TryAdd("vulture", 2)
Console.WriteLine("Added new bird")
' Not reached.
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.
' Part 1: create a dictionary, and add one key.
Dim colors = New Dictionary(Of String, Integer)
' Part 2: replace value at this key with indexer assignment.
colors("blue") = 20
' Part 3: use TryAdd on the same key, which does not update the value.
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 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.