Skip to content

Instantly share code, notes, and snippets.

@robfe
Created April 4, 2013 19:53
Show Gist options
  • Save robfe/5313618 to your computer and use it in GitHub Desktop.
Save robfe/5313618 to your computer and use it in GitHub Desktop.
Dictionary GetOrCreate
public static class Extensions
{
public static TValue GetOrCreate<TKey, TValue>(this Dictionary<TKey, TValue> d, TKey key, Func<TKey, TValue> valueFactory)
{
TValue value;
if (!d.TryGetValue(key, out value))
{
d[key] = value = valueFactory(key);
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment