« Another extension method: DisposeAfter | Main | Finding ancestor elements in WPF »
February 5, 2008
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 at February 5, 2008 5:23 PM
Trackback Pings
TrackBack URL for this entry:
http://blog.logos.com/mt-cgi/mt-tb.cgi/183