Skip to content
mnaoumov.dev
Go back

Useful Dictionary extensions I am always using

There are some of methods I am always creating from scratch for all projects I am working on

public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue = default(TValue))
{
    if (dictionary == null)
        throw new ArgumentNullException("dictionary");

    TValue value;
    return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}
public static TValue GetOrAddValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> valueFactory)
{
    if (dictionary == null)
        throw new ArgumentNullException("dictionary");

    TValue value;
    if (!dictionary.TryGetValue(key, out value))
    {
        value = valueFactory();
        dictionary[key] = value;
    }

    return value;
}

Share this post on:

Previous Post
T4 Templates and Null in Expression block
Next Post
T4 Runtime Template and code-behind logic