Dictionary access
Learn safe access with TryGetValue and ContainsKey.
TryGetValue
If you access a missing key with the indexer, a KeyNotFoundException is thrown. To avoid this, use TryGetValue: it does both the existence check and the value access in a single call.
The call has the form ages.TryGetValue("Alex", out int val). If the key exists, the method returns true and val gets the value; if not, it returns false and val becomes the default value of the type.
ContainsKey
If you only want to check whether a key exists, use ContainsKey: the call ages.ContainsKey("Ayşe") returns a bool. Since TryGetValue combines the check and the access, ContainsKey is rarely needed.
Still, ContainsKey is a readable choice when you only need the existence check, with no need for the value.
Exercise Safe access with TryGetValue
Declare Dictionary<string, int> ages = new Dictionary<string, int>();. Use Add to put 30 under the key "Ayşe". Then search for the key "Mehmet" with ages.TryGetValue("Mehmet", out int val), assigning the result to ok. Finally print ok with Console.WriteLine.
Show example solution
Add with ages.Add("Ayşe", 30);, then try with bool ok = ages.TryGetValue("Mehmet", out int val);, finally print with Console.WriteLine(ok);.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Search for Mehmet with TryGetValue and print the result
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Ayşe", 30);
bool ok = ages.TryGetValue("Mehmet", out int val);
Console.WriteLine(ok);
}
}
Test yourself
-
What does TryGetValue print for a missing key?
Dictionary<string, int> ages = new Dictionary<string, int>(); ages.Add("Ayşe", 30); int val; bool ok = ages.TryGetValue("Alex", out val); Console.WriteLine(ok);- true
- 30
- 0
- false
Show answer
false — Correct. "Alex" is not in the dictionary; TryGetValue returns false.
-
Match each expression to its meaning
- TryGetValue
- Safe access
- ContainsKey
- Key exists?
- dict[key]
- May throw
- out val
- Output parameter
-
ContainsKey call
Dictionary<string, int> ages = new Dictionary<string, int>(); ages.Add("Ayşe", 30); bool has = ____; Console.WriteLine(has);Show answer
Dictionary<string, int> ages = new Dictionary<string, int>(); ages.Add("Ayşe", 30); bool has = ages.ContainsKey("Ayşe"); Console.WriteLine(has);