I prefer to define convenience extension methods for such things. 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); }
No need to worry about the performance of hashing and dictionary lookups - I primarily care about readability and maintainability. Using the above extension methods, this type is single-line:
int value = dict.GetOrSet(key, 0);
(Disclaimer: does not perform an if (condition) check - I rarely experience these scenarios)
Alexfoxgill
source share