TryAdd
In newer versions of .NET, we can use TryAdd
to add values to the Dictionary
. This method will add the value only if the argument key is not already present.
Unlike assigning with the indexer, TryAdd
will not replace existing values at a key. It returns a bool
that tells us whether any value was added.
The TryAdd()
method can be tested, but first we must create a Dictionary
with some sample entries. Do not worry too much about the values in this program.
Dictionary
. We have string
keys and bool
values—and 3 of each.Dictionary
. TryAdd()
returns true, meaning the value was added.Dictionary
, TryAdd()
returns false, and does not mutate the Dictionary
.using System; using System.Collections.Generic; // Step 1: create dictionary. var items = new Dictionary<string, bool>() { { "chair", true }, { "ladder", false }, { "table", true }, }; // Step 2: use TryAdd with key not already present. if (items.TryAdd("wheel", true)) { Console.WriteLine("Added wheel"); } // Step 3: Use TryAdd on key that is found. if (items.TryAdd("chair", true)) { // Not reached. } else { Console.WriteLine("Did not add chair; already added"); }Added wheel Did not add chair; already added
Often we do not need to test the return value of TryAdd
. And by ignoring the return value, our programs can be slightly cleaner and simpler.
foreach
to loop over a string
array and call TryAdd
on each element. Some duplicate strings are not added.using System; using System.Collections.Generic; var cache = new Dictionary<string, bool>(); // Step 1: Add the items with TryAdd. // ... We can ignore the return value if not needed. var items = new string[] { "bird", "bird", "frog", "fish", "frog" }; foreach (var item in items) { cache.TryAdd(item, true); } // Step 2: display the dictionary. foreach (var pair in cache) { Console.WriteLine(pair); }[bird, True] [frog, True] [fish, True]
Though it is a small method, TryAdd
on Dictionary
in C# can improve the readability and clarity of programs. With it we can ignore keys that already have been inserted.