Dictionary<T> look-up or create made simpler
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

8 responses