C# Dictionary Update Value: Indexer vs TryGetValue
Learn how to update values in a C# Dictionary using the indexer and TryGetValue. Compare behavior for existing and missing keys, avoid common pitfalls, and use ConcurrentDictionary for thread-safe updates.

Updating a value in a C# Dictionary<TKey, TValue> is a common operation, but the behavior depends on whether the key already exists. The indexer and TryGetValue are the two primary approaches, and each has distinct semantics for existing and missing keys. This article compares their syntax and behavior, including how to handle missing keys and what changes in concurrent scenarios.
The Indexer: Direct Assignment and Its Behavior
The indexer on Dictionary<TKey, TValue> allows you to assign a value for a given key. If the key exists, the value is replaced. If the key does not exist, the key and value are added. This is the simplest way to update a value, but it also adds a new entry when the key is absent, which may not be what you want.
var dict = new Dictionary<string, int>();
dict["count"] = 1; // adds key "count" with value 1
dict["count"] = 2; // updates value to 2The indexer performs a single lookup and then either updates or inserts. It is efficient and concise. However, if you need to update only when the key already exists, you need a different approach.
Using TryGetValue to Update Only Existing Keys
TryGetValue returns true if the key exists and provides the current value. You can then decide whether to update it. This pattern is useful when you want to avoid adding a new entry for a missing key.
if (dict.TryGetValue("count", out int current))
{
dict["count"] = current + 1;
}
else
{
// handle missing key, e.g., log or throw
}This performs two lookups: one for TryGetValue and one for the indexer assignment. In practice, the overhead is minimal for most applications, but it is worth noting if you are in a tight loop.
Handling Missing Keys: Add vs Update Semantics
The indexer's behavior of adding a missing key is often surprising. If you want to add only if the key does not exist, you can use Add, which throws an ArgumentException if the key already exists. To update only if the key exists, you need TryGetValue or a ContainsKey check.
| Method | Key exists | Key missing | Throws |
|---|---|---|---|
| Indexer assignment | Updates value | Adds key-value pair | No |
| Add | Throws | Adds key-value pair | Yes |
| TryGetValue + assignment | Updates value | Does nothing (if you handle it) | No |
Updating Values in a Concurrent Dictionary
When multiple threads update the same dictionary, the standard Dictionary is not thread-safe. ConcurrentDictionary<TKey, TValue> provides atomic operations. For updating, you can use AddOrUpdate or TryUpdate. AddOrUpdate is a single atomic operation that either adds or updates based on the key's existence.
var concurrent = new ConcurrentDictionary<string, int>();
concurrent.AddOrUpdate("count", 1, (key, oldValue) => oldValue + 1);This is useful for counters or accumulators. TryUpdate allows you to update only if the current value matches an expected value, which is a compare-and-swap pattern.
concurrent.TryUpdate("count", 2, 1); // updates "count" to 2 only if its current value is 1Performance Considerations for Frequent Updates
The indexer is the most direct way to update an existing key and avoids the extra lookup needed by a TryGetValue-plus-assignment pattern. In most applications the extra lookup is minor, but if this pattern appears in a tight loop, profile it to see whether it matters. If the key is guaranteed to exist and you do not need to handle missing keys, the indexer is the simplest choice.
For concurrent scenarios, AddOrUpdate is atomic but has synchronization overhead. TryUpdate is useful for conditional updates, but a separate TryGetValue followed by TryUpdate is not atomic; use AddOrUpdate for read-modify-write operations.
Common Mistakes and Edge Cases
One common mistake is assuming the indexer will throw if the key is missing. It does not; it adds the entry. This can lead to unintended growth of the dictionary. Another edge case is updating a value that is a reference type: the indexer replaces the reference, not mutates the object. If the object is mutable, you can update its properties without reassigning the dictionary entry.
Also, be aware that the indexer's setter is not atomic. In a multi-threaded context, use ConcurrentDictionary to avoid race conditions.
Choosing the Right Update Strategy
The choice depends on whether you need to handle missing keys and whether you are in a concurrent context. For a simple update where the key is guaranteed to exist, use the indexer. If you need to conditionally update, use TryGetValue. For concurrent updates, use AddOrUpdate or TryUpdate. This decision affects correctness and performance.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.