Dictionary Add or Update in C#: Best Way

How-to basics · Updated November 22, 2026

The best way to add or update a key in a .NET Dictionary<TKey, TValue> is to use the indexer: dict[key] = value;. It inserts the key if it doesn’t exist and overwrites the value if it does, making it the simplest and most readable single-line solution for most scenarios.

Why the Indexer Is the Default Choice

The Dictionary<TKey, TValue> class in .NET (since .NET Framework 2.0) provides an indexer property that behaves differently from array indexing. When you write dict[key] = value, the runtime checks whether the key exists:

  • If the key does not exist, it adds a new entry.
  • If the key does exist, it replaces the existing value.

This behavior is documented in the official Microsoft documentation and is consistent across all .NET implementations (Framework, Core, 5+, and .NET 8/9). The indexer is also the fastest way to perform an add-or-update because it avoids the extra lookup that a check-then-add pattern would require.

How the Dictionary Works Internally

Understanding the internal mechanics helps you choose the right method. A .NET dictionary is a hash table. It uses the key’s GetHashCode() method to compute a bucket index, then stores the key-value pair in that bucket. When you use the indexer setter, it performs a single hash lookup:

  1. Compute the hash of the key.
  2. Find the bucket (or probe for an empty slot).
  3. If the key is found, update the value in place.
  4. If not found, add a new entry and increment the Count.

Because the indexer does not require a separate ContainsKey call, it is more efficient than the alternative pattern:

if (dict.ContainsKey(key))
    dict[key] = newValue;
else
    dict.Add(key, newValue);

That pattern performs two lookups (one for ContainsKey, one for the indexer setter). The indexer alone performs one. For most applications the difference is negligible, but in tight loops it matters.

When to Use Add() Instead

The Add(key, value) method is the strict “insert only” operation. It throws an ArgumentException if the key already exists. Use it when you want to enforce that a key is new and you want an exception to signal a bug or an unexpected duplicate. For example, when parsing a file where duplicate keys indicate malformed data:

var dict = new Dictionary<string, int>();
foreach (var line in lines)
{
    var parts = line.Split(',');
    try { dict.Add(parts[0], int.Parse(parts[1])); }
    catch (ArgumentException) { /* log duplicate */ }
}

If you call Add on an existing key, the exception message is: “An item with the same key has already been added.” This can be useful for debugging, but it adds overhead. If you don’t need that safety, prefer the indexer.

Performance and Memory Considerations

For high-performance scenarios, the indexer is the winner. However, there are nuances:

  • Pre-sizing: If you know the approximate number of entries, pass the capacity to the constructor: new Dictionary<string, int>(1000). This avoids resizing overhead (the dictionary grows by doubling its internal array when it reaches a load factor threshold).
  • Value types vs. reference types: For value types like int or struct, the indexer setter overwrites the value in place. For reference types, it replaces the reference. No memory leak occurs, but be aware that the old object becomes eligible for garbage collection.
  • Custom equality comparer: If you use a custom IEqualityComparer<TKey>, the indexer uses that comparer for both hashing and equality. Ensure the comparer is consistent (same hash for equal keys) to avoid undefined behavior.

Common Mistakes and Misconceptions

One frequent mistake is trying to update a value with Add and catching the exception, which is slow and ugly. Another is using ContainsKey followed by indexer, which is redundant. A third misconception is that the indexer getter (dict[key]) throws a KeyNotFoundException when the key is missing—that’s true, but the setter does not throw for missing keys; it adds them.

Another subtle issue: if you are using a Dictionary with a key that is a mutable object, changing the key’s fields after insertion can break the hash table. The dictionary will not rehash automatically. You must remove and re-add the entry. This is a common source of bugs when using custom classes as keys.

Alternatives: TryAdd, TryUpdate, and ConcurrentDictionary

.NET offers more specific methods for certain needs:

  • TryAdd(key, value) (available since .NET Core 2.0 / .NET Standard 2.1) attempts to add and returns false if the key exists, without throwing. It’s a good middle ground.
  • For atomic updates in multithreaded code, use ConcurrentDictionary<TKey, TValue>. It has AddOrUpdate(key, addValue, updateValueFactory) and GetOrAdd(key, valueFactory) methods that are thread-safe. The indexer on ConcurrentDictionary also works but is not atomic for read-modify-write operations.
  • For read-only scenarios, consider ReadOnlyDictionary<TKey, TValue> or FrozenDictionary (in .NET 8+) for performance.

Example with ConcurrentDictionary:

var concurrent = new ConcurrentDictionary<string, int>();
concurrent.AddOrUpdate("key", 1, (k, old) => old + 1);

This adds “key” with value 1 if missing, or increments the existing value. This is the recommended pattern for counters in parallel loops.

Real-World Code Example

Suppose you are counting word frequencies in a text. The natural add-or-update pattern is:

var counts = new Dictionary<string, int>();
foreach (var word in words)
{
    counts[word] = counts.TryGetValue(word, out int count) ? count + 1 : 1;
}

This uses the indexer for the update and TryGetValue to avoid a double lookup. Alternatively, you can use TryAdd with a separate increment, but the above is efficient and clear. For a simpler version that is slightly less efficient but easier to read:

counts[word] = counts.ContainsKey(word) ? counts[word] + 1 : 1;

That does two lookups when the key exists. The TryGetValue version does one lookup total because it retrieves the value in the same call.

Frequently Asked Questions

Does the indexer throw an exception if the key doesn’t exist?
No, the setter (dict[key] = value) never throws for a missing key; it adds it. The getter (value = dict[key]) throws KeyNotFoundException if the key is absent.

What is the difference between Add and indexer?
Add throws if the key exists; the indexer silently overwrites. Use Add when duplicate keys are errors, and the indexer when you want upsert behavior.

Is there a built-in method named

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.