class Cached - Part 1

Here's a nice little helper class that implements a thread safe generic lazy factory and is real easy to use. Create a readonly instance in your constructor, providing the factory method. The first time the actual instance is requested, the factory method is invoked.

internal class Cached<T>  
{
    readonly Func<T> _factory;
    private T _value;
    private bool _initialized;

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

    private T PlainGetter()
    {
        return _value;
    }

    public T Instance
    {
        get
        {
            if (!_initialized)
                lock (_factory)
                    if (!_initialized)
                    {
                        _value = _factory();
                        _initialized = true;
                    }
            return _value;
        }
    }

    public static implicit operator T(Cached<T> cached)
    {
        return cached.Instance;
    }

    public override bool Equals(object obj)
    {
        return Instance.Equals(obj);
    }

    public override int GetHashCode()
    {
        return Instance.GetHashCode();
    }

    public override string ToString()
    {
        return Instance.ToString();
    }
}
Google
m@kli.dk @klinkby RSS feed  GitHub