Dictionary<T> look-up or create made simpler

August 4th 2009 • .NET (, ) • 4,624 views • 9 responses

The design of a Dictionary<T> lends itself well to a caching or identification mechanism and as a result you often see code that looks like this:

private static Dictionary<string,Employee> employees;
…
public static Employee GetByName(string name) {
    Employee employee;
    if (!employees.TryGetValue(name, out employee)) {
        employee = new Employee(whatever);
        employees.Add(name, employee);
    }
    return employee;
}

It’s not that it is particularly difficult but it can be a bit error prone and when you’re doing it over and over. What would be nicer is something that let you do:

public static Employee GetByName(string name) {
    return employees.GetOrAdd(name, () => new Employee(whatever));
}

Here’s an extension method to drop-in to a static class of your choosing that achieves just that.

public static TDictionaryValue GetOrAdd<TKey, TDictionaryValue>(this IDictionary<TKey, TDictionaryValue> dictionary, TKey key, Func<TDictionaryValue> newValue)
{
    TDictionaryValue value;
    if (!dictionary.TryGetValue(key, out value)) {
        value = newValue.Invoke();
        dictionary.Add(key, value);
    }
    return value;
}

[)amien

Related content

9 responses  

  1. Nick on August 4th, 2009

    Heya Damien, did you mean to use the non-generic IDictionary interface in your static method signatures?

  2. Damien Guard on August 4th, 2009

    Oops, the code was right on my VS box but going from code to HTML I’d missed a couple of those pesky < bits :D

    Thanks for the heads-up.

    [)amien

  3. David Fowler on August 5th, 2009

    Why do you call invoke on the delegate instead of using () to execute?

    Also checkout http://blogs.msdn.com/wesdyer/archive/2007/01/26/function-memoization.aspx

    Functional programming for life!

  4. Pingback Dew Drop – August 5, 2009 | Alvin Ashcraft's Morning Dew on August 5th, 2009

    [...] Dictionary look-up or create made simpler (Damien Guard) [...]

  5. Will on August 5th, 2009

    Nice one

    Definitely I have to get used to the use of extension methods, it seems really obvious after you’ve seen it, but if you haven’t used extension methods it is hard for it to “pop up” :P

    Cheers!

  6. Roger Pence on August 5th, 2009

    This is great! I love it when I can learn as much reading ~30 lines of code than I can having read an entire chapter in a book. rp

  7. Brad Wilson on August 7th, 2009

    Using double checked locking without knowing that the variable in question is marked “volatile” is a potential source of threading errors.

  8. Pingback Interesting Finds: 2009 08.04 ~ 08.10 - gOODiDEA.NET on August 9th, 2009

    [...] Dictionary<T> look-up or create made simpler [...]

  9. Mike Brown on August 27th, 2010

    Interesting that this became a function on the ConcurrentDictionary class in .NET 4 ;)

Leave your response

  1. (kept private)