Last Updated: February 25, 2016
·
908
· chriseldredge

c# subclass Lazy<T>

Lazy<T> provides a built in method of initializing an instance on demand with optional synchronization for thread safety. You may want to inherit from Lazy<T> for polymorphism, but find it tricky to write a constructor that can reference an instance based delegate to use as the valueFactory.

Here's a technique to accomplish this goal.

public class LinkedRecord : Lazy<object>
{
    public LinkedRecord(int key)
        :this(new Loader(key))
    {
    }

    private LinkedProperty(Loader loader)
        : base(loader.GetValue, LazyThreadSafetyMode.None)
    {
    }

    private class Loader
    {
        private readonly string _key;

        public Loader(int key)

        {
            this._key = key;

        }

        public object GetValue()
        {
            // expensive initialization goes here
        }
    }
}