GetOrAddValue

Jon Skeet recently posted his DictionaryUtility.GetOrCreate method.

Here’s our version (sans-parameter validation):

    public static TValue GetOrAddValue<TKey, TValue>(
        this IDictionary<TKey, TValue> dict, TKey key)
        where TValue : new()
    {
        TValue value;
        if (dict.TryGetValue(key, out value))
            return value;
        value = new TValue();
        dict.Add(key, value);
        return value;
    }
    public static TValue GetOrAddValue<TKey, TValue>(
        this IDictionary<TKey, TValue> dict, TKey key,
        Func<TValue> generator)
    {
        TValue value;
        if (dict.TryGetValue(key, out value))
            return value;
        value = generator();
        dict.Add(key, value);
        return value;
    }

First note that we have an overload that takes a Func<TValue>. This enables us to call GetOrAddValue even for types that don’t support a parameterless constructor. We pass a Func<TValue> rather than a TValue to avoid needlessly creating empty instances when they already exist in the dictionary.

Also, since we’re using the looked-up value if it exists, we call TryGetValue instead of checking ContainsKey.

Posted by Jacob Carpenter on February 05, 2008