C# Dictionary.TryGetValue: Handle Missing Keys Without Exceptions
A dictionary lookup often asks a simple question: “Do we have a value for this key?” If you use the indexer and the key is absent, C# throws KeyNotFoundException. That is useful when absence signals a programming bug, but it is awkward when missing keys are an expected part of normal input.
TryGetValue gives you both outcomes in one call: a Boolean that says whether the key exists, and an out value that contains the result when it does. This guide shows when to use it, how to handle a missing entry, and where its limits are.

Editorial illustration.
Summary
- Use
TryGetValuewhen a key may reasonably be absent, such as a user-entered code or optional configuration entry. - It combines checking and retrieving into one lookup, avoiding a separate
ContainsKeycall followed by the indexer. - Decide what a missing key means in your application; do not silently turn every absence into a default value.
A complete example
This is a .NET 10 console example using the standard collections library. The code uses basic C# syntax and also works in .NET 8 or later; it does not depend on a C# 14 language feature:
var rates = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase)
{
["USD"] = 1.00m,
["EUR"] = 0.92m,
["MYR"] = 4.70m
};
Console.Write("Currency code: ");
string code = Console.ReadLine()?.Trim() ?? "";
if (rates.TryGetValue(code, out decimal rate))
{
Console.WriteLine($"Rate for {code.ToUpperInvariant()}: {rate}");
}
else
{
Console.WriteLine($"No rate is configured for '{code}'.");
}
The TryGetValue return value answers whether the key was found. When it returns true, rate contains the mapped value. When it returns false, the out value is the default for its type—in this case 0m. The example does not use that default on failure; it follows the else branch and reports the missing code instead.
The dictionary uses StringComparer.OrdinalIgnoreCase, so usd and USD match. That choice is deliberate for these three-letter codes. For user names, file paths or culture-sensitive text, choose comparison behavior according to the domain; don’t assume every string key should ignore case.
Why not check ContainsKey first?
This pattern makes two lookups when the key exists:
if (rates.ContainsKey(code))
{
decimal rate = rates[code];
}
Between the check and the indexer, a mutable dictionary could also be changed by another part of the program. Dictionary<TKey,TValue> is not designed for concurrent writes without synchronization. In ordinary single-threaded code, the main issue is redundant work and extra branches; in concurrent code, use an appropriate synchronization strategy or a concurrent collection.
The more direct version is:
if (rates.TryGetValue(code, out decimal rate))
{
// Use rate here.
}
Microsoft documents TryGetValue as combining the work of ContainsKey and the indexer. It is generally the clearest choice when a missing key is expected. The method approaches an O(1) operation for Dictionary, but the important benefit for most application code is expressing the success and failure paths explicitly.
Choose what “not found” should mean
A missing entry can mean different things, and the code should show which case applies.
The key is optional
For optional user input, show a useful message, ask for a different value, or return a nullable result from a helper method. Do not throw an exception simply because a user typed a currency code that your application does not support.
The key is required configuration
If a missing value means the application is misconfigured, fail clearly at the boundary where configuration is loaded. You can still use TryGetValue to produce a precise error such as “Required rate EUR is missing,” then stop startup or return a configuration error. The point is not to hide an invalid state; it is to report it intentionally.
The key should always exist
If the dictionary is built internally and a missing key proves a logic error, the indexer may be appropriate because its exception exposes the broken assumption. Another option is a helper that throws a domain-specific exception. TryGetValue is not a rule that every dictionary access must follow.
Reference values and nullable annotations
For a dictionary whose value is a reference type, a failed lookup returns null as the out value. With nullable reference types enabled, the compiler’s annotations help communicate that possibility. For example:
if (usersByEmail.TryGetValue(email, out User? user))
{
Console.WriteLine(user.DisplayName);
}
Here the dictionary can return a user only when the key exists; still consider whether the dictionary deliberately permits null values. If null is itself a valid stored value, the Boolean and the value are separate pieces of information: true with null means a key exists and maps to null, while false means no key exists. Prefer not to store null values when that distinction would make calling code confusing.
With value types such as int, decimal or bool, a missing lookup yields zero, 0m or false. Those values may also be legitimate entries. Never infer “not found” from the out value alone; use the Boolean result.
A small helper when callers need the same policy
If several parts of an application need identical validation, wrap the lookup and its policy rather than repeating slightly different messages:
static decimal GetRequiredRate(
IReadOnlyDictionary<string, decimal> rates,
string code)
{
if (rates.TryGetValue(code, out decimal rate))
{
return rate;
}
throw new InvalidOperationException(
$"No exchange rate is configured for '{code}'.");
}
Accepting IReadOnlyDictionary communicates that this helper only reads. The exception type and message should fit the application; a web API may instead return a validation response, while a startup routine may reject invalid configuration.
Mistakes to avoid
- Calling
ContainsKeyand then indexing for every normal lookup. - Ignoring the Boolean and using the default
outvalue as if it proved the key existed. - Catching
KeyNotFoundExceptionas the routine path for user input. - Assuming string key comparisons are case-insensitive by default.
- Treating
TryGetValueas thread-safety for a dictionary that is being modified concurrently. - Swallowing a missing required setting instead of reporting a clear configuration error.
For nearby C# examples, see using SearchValues<T> for repeated text matching and using FrozenDictionary for read-heavy lookup data. Those tools solve different workload problems; a normal mutable Dictionary remains a good default for most key-to-value maps.
My Take
I reach for TryGetValue when “not found” is part of the input contract, not as a reflex for every access. Its Boolean makes the branch explicit, and it nudges the code to decide whether absence is expected, invalid or impossible.
Bottom Line
Use TryGetValue to handle a possibly missing dictionary key in one clear lookup. Use the Boolean as the source of truth, and choose an error, fallback or not-found response that matches the data’s role.