dict.TryGetValue() / ContainsKey()
Methods for safely retrieving values from a dictionary with TryGetValue(), and checking whether a specified key exists with ContainsKey().
Syntax
using System.Collections.Generic; // Returns true and the value if the key exists; returns false and the default value if it does not. dictionary.TryGetValue(TKey key, out TValue value) // Returns true if the specified key exists in the dictionary. dictionary.ContainsKey(TKey key) // Returns true if the specified value exists in the dictionary (unlike key lookup, this is an O(n) operation). dictionary.ContainsValue(TValue value)
Method List
| Method | Description |
|---|---|
| TryGetValue(TKey key, out TValue value) | Returns true if the key exists, storing the value in the out parameter. Returns false if the key does not exist, and value is set to the default value for its type. |
| ContainsKey(TKey key) | Returns true if the dictionary contains the specified key. Uses hashing to search in O(1). |
| ContainsValue(TValue value) | Returns true if the dictionary contains the specified value. Iterates through all entries internally, making it an O(n) operation. |
Sample Code
using System;
using System.Collections.Generic;
Dictionary<string, int> scores = new Dictionary<string, int>
{
{ "Alice", 85 },
{ "Bob", 92 },
{ "Carol", 78 }
};
// Safely retrieve a value using TryGetValue().
if (scores.TryGetValue("Bob", out int bobScore))
{
Console.WriteLine($"Bob's score: {bobScore}"); // Bob's score: 92
}
// Returns false if the key does not exist.
if (!scores.TryGetValue("Dave", out int daveScore))
{
Console.WriteLine($"No data for Dave. Value: {daveScore}"); // Value: 0 (default)
}
// Check with ContainsKey() before adding a new entry.
string newKey = "Dave";
if (!scores.ContainsKey(newKey))
{
scores.Add(newKey, 70);
Console.WriteLine($"Added {newKey}.");
}
// Check whether a value exists using ContainsValue().
Console.WriteLine(scores.ContainsValue(92)); // True
Console.WriteLine(scores.ContainsValue(100)); // False
Notes
Accessing a dictionary with dictionary[key] throws a KeyNotFoundException if the key does not exist. When you need to check for a key before retrieving its value, a single call to TryGetValue() is more efficient than the two-step approach of using if + ContainsKey().
For retrieving and iterating over dictionary keys and values, see Keys / Values / foreach.
If you find any errors or copyright issues, please contact us.