class Cached - Part 2

Here's another useful little helper class that implements a thread safe generic lazy factory that's real easy to use. Create a readonly instance in your constructor, providing the factory method. The factory takes a parameter, that is as parameter to create the value, as well as look up the value the next time it is requested.

internal class Cached<T, U>  
{
    readonly Func<T, U> _factory;
    readonly Dictionary<U, T> _cache = new Dictionary<U, T>();

    public Cached(Func<T, U> factory)
    {
        if (factory == null)
            throw new ArgumentNullException("factory");
        _factory = factory;
    }

    public T this[U seed]
    {
        get {
            T value;
            if (!_cache.TryGetValue(seed, out value))
                lock(_cache)
                    if (!_cache.TryGetValue(seed, out value))
                        _cache.Add(seed, value = _factory(seed));
            return value;
        }
    }
}
Google
m@kli.dk @klinkby RSS feed  GitHub