Skip to content
Tutorials Center
My learning

Topics

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.

C#
if (prices.TryGetValue("apple", out decimal price))
{
    Console.WriteLine(price);
}

Try it

C# Reading safely

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.

C# Counting, grouping and updating

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

C#
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

  • TryGetValue is the standard read. It does one hash lookup, whereas ContainsKey followed by the indexer does two.
  • The out value is meaningless when the result is false. It is 0, null or false. Do not use it without checking.
  • GetValueOrDefault does not add the key. It only reads. The default 0 for int cannot be told apart from a stored 0; use TryGetValue when that matters.
  • Counting: d[k] = d.GetValueOrDefault(k) + 1 is simple and readable. CollectionsMarshal.GetValueRefOrAddDefault is faster because it looks up once.
  • Never keep the ref across changes. Adding another key can resize the table and make an earlier ref point to stale storage.
  • Removal while enumerating is permitted for Dictionary since .NET Core 3.0. Adding a new key during enumeration is not allowed and throws InvalidOperationException. Other collection types do not make this exception, so do not generalize.
  • Lazy initialization: dict.TryGetValue(k, out var v) followed by dict[k] = v = Create() is the usual cache pattern. For concurrent code use ConcurrentDictionary.GetOrAdd.
  • Do not combine ??= with the indexer. (map[k] ??= []).Add(x) fails for a missing key because the indexer getter throws before ??= can assign. Use TryGetValue or GetValueRefOrAddDefault.