How to Use TryGetValue in Dictionary C# - Simple Guide
Use
TryGetValue to safely check if a key exists in a Dictionary and get its value without throwing an exception. It returns true if the key is found and outputs the value; otherwise, it returns false.Syntax
The TryGetValue method has this syntax:
dictionary.TryGetValue(key, out value)
Here, key is the key you want to find, and value is an output variable that will hold the value if the key exists.
The method returns true if the key is found, otherwise false.
csharp
bool TryGetValue(TKey key, out TValue value);
Example
This example shows how to use TryGetValue to get a value safely from a dictionary without causing an error if the key is missing.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { var ages = new Dictionary<string, int> { {"Alice", 30}, {"Bob", 25} }; if (ages.TryGetValue("Alice", out int aliceAge)) { Console.WriteLine($"Alice's age is {aliceAge}."); } else { Console.WriteLine("Alice not found."); } if (ages.TryGetValue("Charlie", out int charlieAge)) { Console.WriteLine($"Charlie's age is {charlieAge}."); } else { Console.WriteLine("Charlie not found."); } } }
Output
Alice's age is 30.
Charlie not found.
Common Pitfalls
Common mistakes when using TryGetValue include:
- Not using the
outkeyword for the value parameter. - Assuming the method throws an exception if the key is missing (it does not).
- Ignoring the boolean result and using the output value without checking if the key exists.
Always check the returned boolean before using the output value.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { var dict = new Dictionary<string, int> { {"key1", 100} }; // Wrong: ignoring the boolean result dict.TryGetValue("key2", out int value); Console.WriteLine(value); // value is 0, but key2 does not exist // Right: check the result before using value if (dict.TryGetValue("key2", out int safeValue)) { Console.WriteLine(safeValue); } else { Console.WriteLine("Key not found."); } } }
Output
0
Key not found.
Quick Reference
Remember these tips when using TryGetValue:
- Use
outkeyword for the value parameter. - Check the boolean result before using the value.
- It avoids exceptions from missing keys.
- Works faster than using
ContainsKeythen indexing.
Key Takeaways
TryGetValue safely checks for a key and gets its value without exceptions.
Always use the out parameter and check the method's boolean result before using the value.
It is more efficient than checking ContainsKey then accessing the dictionary.
If the key is missing, the out value is set to the default for the value type.
Avoid ignoring the boolean result to prevent using invalid values.