In C#, Dictionary.TryGetValue(key, out value) is the safest way to read a value. It looks up the key once. If the key exists, it returns true and puts the value in the out variable.
If the key is missing, it returns false and sets the out variable to the default of the type: 0 for numbers, false for bool, and null for reference types. The indexer d[key] would throw KeyNotFoundException instead.
This is an instance member of Dictionary<TKey,TValue> (System.Collections.Generic). Call it on a dictionary variable, such as ages.TryGetValue(...). A dictionary is a class, so two variables can share one dictionary.
Syntax
Pass the key and an out variable. You can declare the variable right inside the call.
C#
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25);
if (ages.TryGetValue("Asha", out int age)) {
Console.WriteLine(age); // 25
}
bool found = ages.TryGetValue("Zed", out int none); // false, none is 0
Call
What it does
ages.TryGetValue("Asha", out int age)
Returns true and sets age to the stored value.
ages.TryGetValue("Zed", out int none)
Returns false and sets none to 0.
ages["Zed"]
The indexer throws KeyNotFoundException for a missing key.
A null key throws ArgumentNullException. The out variable is always assigned, so you can read it even when the result is false (but then it only holds the default).
Library declarations
C#
public bool TryGetValue(TKey key, out TValue value);
Parameters
Parameter
Description
key
Required. The key to look for. It must not be null.
value
Output. Receives the stored value when the key is found, or the default value of TValue when it is not.
Return Value
Return Value
Description
bool
true if the key was found; otherwise false.
C# Examples
Example 1 — Read a Present and a Missing Key
Call TryGetValue for one key that exists and one that does not, and print both results.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25);
ages.Add("Ravi", 31);
bool foundAsha = ages.TryGetValue("Asha", out int a);
Console.WriteLine(foundAsha);
Console.WriteLine(a);
bool foundZed = ages.TryGetValue("Zed", out int z);
Console.WriteLine(foundZed);
Console.WriteLine(z);
}
}
Output
True
25
False
0
How It Works
Inline out variable.out int a declares a and fills it in one step.
Hit."Asha" exists, so the call returns True and a becomes 25.
Miss."Zed" does not exist, so the call returns False without throwing.
Default value. After a miss, z holds 0, the default for int. Check the bool before you trust it.
Example 2 — Count Words with One Lookup
Use the default-zero trick: a missing word gives 0, so adding 1 works for new and old words alike.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
string[] words = { "red", "blue", "red", "red" };
Dictionary<string, int> counts = new Dictionary<string, int>();
foreach (string w in words) {
counts.TryGetValue(w, out int current);
counts[w] = current + 1;
}
Console.WriteLine(counts["red"]);
Console.WriteLine(counts["blue"]);
Console.WriteLine(counts.Count);
}
}
Output
3
1
2
How It Works
Result ignored. The loop does not use the bool; it only needs current.
New word. For the first "red" the key is missing, so current is the default 0 and counts[w] is set to 1.
Known word. For later "red" words, current is the stored count, and the indexer writes back count plus 1.
Final totals."red" is 3, "blue" is 1, and there are 2 keys. Each word used only one read lookup.
Example 3 — Use a Default When the Key Is Missing
Read a setting, fall back to "en" if it is not there, and compare with the indexer that throws.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, string> settings = new Dictionary<string, string>();
settings.Add("theme", "dark");
if (!settings.TryGetValue("theme", out string theme)) {
theme = "light";
}
Console.WriteLine(theme);
if (!settings.TryGetValue("lang", out string lang)) {
lang = "en";
}
Console.WriteLine(lang);
try {
Console.WriteLine(settings["lang"]);
} catch (KeyNotFoundException) {
Console.WriteLine("Key not found");
}
}
}
Output
dark
en
Key not found
How It Works
Present key."theme" exists, so the if body is skipped and theme stays "dark".
Missing key."lang" is not stored, so TryGetValue returns false and lang is null for a moment.
Fallback assigned. The ! flips the result, so the body runs and sets lang to "en".
Indexer contrast.settings["lang"] has no safe fallback and throws KeyNotFoundException, which the catch block reports.
Frequently Asked Questions
TryGetValue(key, out value) looks up the key once. It returns true and the value if the key exists, or false and the default value if it does not.
The indexer throws KeyNotFoundException for a missing key. TryGetValue never does, so it is the safe choice.
Use TryGetValue when you need the value. ContainsKey followed by d[key] looks up twice, while TryGetValue looks up once.
It is the default of the value type: 0 for int, false for bool, and null for classes such as string.
No. A null key throws ArgumentNullException, just like ContainsKey and the indexer.