dict.TryGetValue() / ContainsKey()
| Since: | C# 2.0(2005) |
|---|
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
Program.cs
using System;
using System.Collections.Generic;
Dictionary<string, int> scores = new Dictionary<string, int>
{
{ "Kogami Shinya", 85 },
{ "Tsunemori Akane", 92 },
{ "Ginoza Nobuchika", 78 }
};
// Safely retrieve a value using TryGetValue().
if (scores.TryGetValue("Tsunemori Akane", out int tsunemoriScore))
{
Console.WriteLine($"Tsunemori Akane's score: {tsunemoriScore}"); // Tsunemori Akane's score: 92
}
// Returns false if the key does not exist.
if (!scores.TryGetValue("Masaoka Tomomi", out int masaokaScore))
{
Console.WriteLine($"No data for Masaoka. Value: {masaokaScore}"); // Value: 0 (default)
}
// Check with ContainsKey() before adding a new entry.
string newKey = "Masaoka Tomomi";
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
Run the following command:
dotnet run Tsunemori Akane's score: 92 No data for Masaoka. Value: 0 Added Masaoka Tomomi. True False
Practical Pattern: Using a Dictionary as a Cache
TryGetValue() is commonly used in cache read/write patterns. If the key exists, retrieve from the cache; otherwise, compute and store the result.
CacheSample.cs
using System;
using System.Collections.Generic;
Dictionary<string, string> cache = new Dictionary<string, string>();
string GetData(string key)
{
if (cache.TryGetValue(key, out string cached))
{
Console.WriteLine($"Cache hit: {key}");
return cached;
}
string value = $"Data:{key} (computed)";
cache[key] = value;
Console.WriteLine($"Cache miss: computed {key}.");
return value;
}
Console.WriteLine(GetData("Kogami Shinya"));
Console.WriteLine(GetData("Tsunemori Akane"));
Console.WriteLine(GetData("Kogami Shinya")); // retrieved from cache on second call
Run the following command:
dotnet run Cache miss: computed Kogami Shinya. Data:Kogami Shinya (computed) Cache miss: computed Tsunemori Akane. Data:Tsunemori Akane (computed) Cache hit: Kogami Shinya Data:Kogami Shinya (computed)
Common Mistakes
Common Mistake: Accessing a Non-Existent Key with the Indexer
Using dict[key] to access a key that does not exist throws a KeyNotFoundException. When a key's existence is uncertain, use TryGetValue() instead.
using System;
using System.Collections.Generic;
// NG: accessing a non-existent key via the indexer
Dictionary<string, int> scores = new Dictionary<string, int>
{
{ "Kogami Shinya", 85 }
};
// int score = scores["Masaoka Tomomi"]; // KeyNotFoundException!
The same logic can also be written as:
using System;
using System.Collections.Generic;
// OK: use TryGetValue() to retrieve safely
Dictionary<string, int> scores = new Dictionary<string, int>
{
{ "Kogami Shinya", 85 }
};
if (scores.TryGetValue("Masaoka Tomomi", out int score))
{
Console.WriteLine($"Score: {score}");
}
else
{
Console.WriteLine("Data not found.");
}
Run the following command:
dotnet run Data not found.
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.