Let's try to resolve a pretty regular case - some kind of key-value static cache. If there is no stored value for the specified key, the cache will call some external routine to get value and add it to the internal dictionary.
Here is a naive approach of the cache. It is straightforward enough.
public class Cache<TKey, TValue>
{
Func<TKey, TValue> _resolver;
Dictionary<TKey, TValue> _cache = new Dictionary<TKey, TValue>();
public Cache(Func<TKey, TValue> resolver)
{
_resolver = resolver;
}
public TValue this[TKey key]
{
get
{
TValue value;
if (!_cache.TryGetValue(key, out value))
{
value = _resolver(key);
_cache.Add(key, value);
}
return value;
}
}
}
And also somewhere in a client code:
class ClientCode
{
static Cache<TKey, TValue> _cache = new Cache<TKey, TValue>(Resolver);
}
Where
Resolver
is an user-defined function to get a value from the outer source.