The IDictionary<TKey, TValue> interface provides a TryGetValue method, but has the disadvantage of requiring the use of an out parameter.

While this method provides a boolean return value that can be used to determine if the key has been found or not, part of the time the code only needs to get a default value if nothing has been found.

Umbrella provides this construct with the GetValueOrDefault extension method :

    var dict = new[] { "A", "B", "C" }
                .ToDictionary(v => "A" + v);

    Assert.AreEqual(dict.GetValueOrDefault("AD"), null);
    Assert.AreEqual(dict.GetValueOrDefault("AD", "N/A"), "N/A");
    Assert.AreEqual(dict.GetValueOrDefault("AC", "N/A"), "C");

Last edited Feb 24, 2009 at 3:09 AM by jlaban, version 1


Qwertie Apr 26, 2011 at 12:32 AM 
For consistency I'd still name it TryGetValue. I'd also like a "TryGetValueSafe" or "SafeGetValue" which does not stupidly throw an exception if key == null (Earth to Microsoft: the reason we call TryGetValue in the first place is to avoid an exception!)