Dictionary returning a default value if the key does not exist

Posted by wasatz on Stack Overflow See other posts from Stack Overflow or by wasatz
Published on 2010-04-08T16:04:18Z Indexed on 2010/04/08 16:43 UTC
Read the original article Hit count: 647

Filed under:
|
|

I find myself using the current pattern quite often in my code nowadays

var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary

var somethingElse = dictionary.ContainsKey(key) ? dictionary[key] : new List<othertype>();
// Do work with the somethingelse variable

Or sometimes

var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary

IList<othertype> somethingElse;
if(!dictionary.TryGetValue(key, out somethingElse) {
    somethingElse = new List<othertype>();
}

Both of these ways feel quite roundabout. What I really would like is something like

dictionary.GetValueOrDefault(key)

Now, I could write an extension method for the dictionary class that does this for me, but I figured that I might be missing something that already exists. SO, is there a way to do this in a way that is more "easy on the eyes" without writing an extension method to dictionary?

© Stack Overflow or respective owner

Related posts about c#

Related posts about collections