Home
C#
Dictionary TryAdd Example
This page was last reviewed on Oct 26, 2023.
Dot Net Perls
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.
bool
Dictionary
Example. 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.
Step 1 We create our Dictionary. We have string keys and bool values—and 3 of each.
Step 2 Here we try to add a key that is not yet in the Dictionary. TryAdd() returns true, meaning the value was added.
Step 3 If a key is already present within the 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
Ignore return value. 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.
Step 1 We use foreach to loop over a string array and call TryAdd on each element. Some duplicate strings are not added.
foreach
Step 2 We display the dictionary. The duplicate strings were silently ignored, and in some programs this may be desired.
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]
Summary. 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.
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.
This page was last updated on Oct 26, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.