The problem is that Dictionary<TKey, TValue> allows you to store null as a value, so you donβt know if the key existed or just had null . Another problem is that null is only applicable to TValue types that are reference types (or Nullable<T> ).
Now that you have said, you yourself can write an extension method:
public static class DictionaryUtilities { public static TValue SafeGet<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultIfNotFound = default(TValue)) { TValue value; return dict.TryGetValue(key, out value) ? value : defaultIfNotFound; } }
So you can query your dictionary as follows:
var sample = new Dictionary<int, string> { {1, "One"}, {2, "Two}, {3, "Three"} }; var willBeNull = sample.SafeGet(4); var willBeHi = sample.SafeGet(4, "HI!");
Although, of course, the above code will return the default values ββof value types if TValue was a value type (that is, if the value type was int , it would return 0 if not found, by default.)
Again, however, you can create two forms where TValue limited to a class and one to a struct , which allows you to return Nullable<T> value types ...