Skip to content

Instantly share code, notes, and snippets.

@jameshulse
Created October 18, 2013 01:26
Show Gist options
  • Save jameshulse/7035070 to your computer and use it in GitHub Desktop.
Save jameshulse/7035070 to your computer and use it in GitHub Desktop.
Lazy dictionary
public class LazyDictionary<TKey, TValue>
{
private readonly Func<TKey, TValue> _factory;
private readonly Dictionary<TKey, TValue> _cache;
public LazyDictionary(Func<TKey, TValue> factory)
{
_factory = factory;
_cache = new Dictionary<TKey, TValue>();
}
public TValue this[TKey key]
{
get
{
if (!_cache.ContainsKey(key))
{
_cache.Add(key, _factory(key));
}
return _cache[key];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment