I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?
A helper class is handy:
public static class DictionaryHelper
{
public static TVal Get<TKey, TVal>(this Dictionary<TKey, TVal> dictionary, TKey key, TVal defaultVal = default(TVal))
{
TVal val;
if( dictionary.TryGetValue(key, out val) )
{
return val;
}
return defaultVal;
}
}
If you're just checking before trying to add a new value, use the ContainsKey method:
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
}
If you're checking that the value exists, use the TryGetValue method as described in Jon Skeet's answer.
Consider the option of encapsulating this particular dictionary and provide a method to return the value for that key:
public static class NumbersAdapter
{
private static readonly Dictionary<string, string> Mapping = new Dictionary<string, string>
{
["1"] = "One",
["2"] = "Two",
["3"] = "Three"
};
public static string GetValue(string key)
{
return Mapping.ContainsKey(key) ? Mapping[key] : key;
}
}
Then you can manage the behaviour of this dictionary.
For example here: if the dictionary doesn't have the key, it returns key that you pass by parameter.