I prefer to define convenience extension methods for things like this. For example:
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
TValue value;
return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}
public static TValue GetOrSet<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
return dictionary[key] = dictionary.GetValueOrDefault(key, value);
}
There is little need to worry about performance of dictionary hashing & lookups - I am primarily concerned with readability and maintainability. With the above extension methods, this kind of thing is a one-liner:
int value = dict.GetOrSet(key, 0);
(Disclaimer: doesn't perform the if (condition)
check - I rarely experience these scenarios)