How to Get Value by Key in Dictionary C# - Simple Guide
In C#, you can get a value from a
Dictionary by using the key inside square brackets like dictionary[key]. To safely get a value without errors if the key is missing, use dictionary.TryGetValue(key, out value) which returns a boolean indicating success.Syntax
There are two common ways to get a value by key from a Dictionary<TKey, TValue> in C#:
- Indexer syntax:
dictionary[key]returns the value for the given key. - TryGetValue method:
dictionary.TryGetValue(key, out value)tries to get the value safely without throwing an error if the key does not exist.
csharp
var value = dictionary[key]; bool found = dictionary.TryGetValue(key, out var value);
Example
This example shows how to get a value by key using both the indexer and TryGetValue. It also shows how to handle a missing key safely.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { var capitals = new Dictionary<string, string> { {"France", "Paris"}, {"Japan", "Tokyo"}, {"Brazil", "Brasilia"} }; // Using indexer - throws if key not found Console.WriteLine(capitals["Japan"]); // Output: Tokyo // Using TryGetValue - safe way if (capitals.TryGetValue("Germany", out string capital)) { Console.WriteLine(capital); } else { Console.WriteLine("Key not found."); } } }
Output
Tokyo
Key not found.
Common Pitfalls
Using the indexer dictionary[key] will throw a KeyNotFoundException if the key does not exist. To avoid this, use TryGetValue which returns false if the key is missing and does not throw an error.
Also, avoid checking dictionary.ContainsKey(key) followed by accessing dictionary[key] because it causes two lookups. TryGetValue is more efficient.
csharp
var dict = new Dictionary<int, string>(); // Wrong: throws exception if key missing // var value = dict[1]; // Better: safe access if (dict.TryGetValue(1, out var value)) { Console.WriteLine(value); } else { Console.WriteLine("Key not found."); }
Output
Key not found.
Quick Reference
| Method | Usage | Behavior |
|---|---|---|
| Indexer | dictionary[key] | Returns value or throws if key missing |
| TryGetValue | dictionary.TryGetValue(key, out value) | Returns true if key found, false otherwise without exception |
Key Takeaways
Use dictionary[key] to get a value but it throws if the key is missing.
Use dictionary.TryGetValue(key, out value) to safely get a value without exceptions.
Avoid checking ContainsKey before accessing the indexer to improve performance.
TryGetValue returns a boolean indicating if the key exists and outputs the value if found.
Always handle the case when a key might not be present to prevent runtime errors.