C# Reference ยท Collections
Dictionary operations: TryGetValue, GetValueOrDefault, TryAdd
Reference for everyday Dictionary operations in C#: TryGetValue, GetValueOrDefault, TryAdd, counting, grouping, updating in place and removing during a loop.
Reading a missing key with the dictionary indexer throws KeyNotFoundException, and adding an existing key with Add throws ArgumentException. The "try" methods avoid both exceptions and avoid hashing the key twice: TryGetValue reads, TryAdd inserts only if absent, and Remove(key, out value) deletes and hands back the old value.
GetValueOrDefault is an extension method (from System.Collections.Generic.CollectionExtensions) that returns a fallback when the key is absent. Together these methods cover almost every dictionary pattern: counting, grouping, caching and updating.
if (prices.TryGetValue("apple", out decimal price)) { Console.WriteLine(price); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public bool TryGetValue(TKey key, out TValue value); public bool TryAdd(TKey key, TValue value); public bool Remove(TKey key, out TValue value); // System.Collections.Generic.CollectionExtensions public static TValue? GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> d, TKey key); public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> d, TKey key, TValue defaultValue); // System.Runtime.InteropServices.CollectionsMarshal public static ref TValue? GetValueRefOrNullRef<TKey, TValue>(Dictionary<TKey, TValue> d, TKey key); public static ref TValue? GetValueRefOrAddDefault<TKey, TValue>(Dictionary<TKey, TValue> d, TKey key, out bool exists);
| Name | Description |
|---|---|
key |
The key to look up. null keys throw ArgumentNullException. |
value (out) |
Receives the stored value, or default(TValue) if the key is missing. For Remove, receives the removed value. |
defaultValue |
Returned by GetValueOrDefault when the key is absent. |
exists (out) |
true if the key was already present, false if the call just added it. |
Returns: TryGetValue, TryAdd and Remove(key, out value) return true on success and false otherwise. GetValueOrDefault returns the value or the fallback (default if none is given).
Errors: ArgumentNullException for a null key. Nothing throws for a missing key.
Usage notes
TryGetValueis the standard read. It does one hash lookup, whereasContainsKeyfollowed by the indexer does two.- The
outvalue is meaningless when the result isfalse. It is0,nullorfalse. Do not use it without checking. GetValueOrDefaultdoes not add the key. It only reads. The default0forintcannot be told apart from a stored0; useTryGetValuewhen that matters.- Counting:
d[k] = d.GetValueOrDefault(k) + 1is simple and readable.CollectionsMarshal.GetValueRefOrAddDefaultis faster because it looks up once. - Never keep the
refacross changes. Adding another key can resize the table and make an earlierrefpoint to stale storage. - Removal while enumerating is permitted for
Dictionarysince .NET Core 3.0. Adding a new key during enumeration is not allowed and throwsInvalidOperationException. Other collection types do not make this exception, so do not generalize. - Lazy initialization:
dict.TryGetValue(k, out var v)followed bydict[k] = v = Create()is the usual cache pattern. For concurrent code useConcurrentDictionary.GetOrAdd. - Do not combine
??=with the indexer.(map[k] ??= []).Add(x)fails for a missing key because the indexer getter throws before??=can assign. UseTryGetValueorGetValueRefOrAddDefault.