#947 – Specifying Lazy Instantiation Using a Lambda Expression
October 8, 2013 2 Comments
When you are declaring an object that will be lazily instantiated, you pass a delegate instance to the Lazy<T> constructor, where the delegate instance indicates a method to be called that will instantiate the underlying object.
For example, you could do the following:
private static Lazy<Dog> dog1 = new Lazy<Dog>(CreateDefaultDog); private static Dog CreateDefaultDog() { return new Dog("Lassie"); }
Very often, however, you’ll want to pass some parameter value to the delegate or just invoke one of the normal constructors for the object, passing one or more parameters to the constructor. You can do this by just using a lambda expression, as follows:
private static Lazy<Dog> dog2 = new Lazy<Dog>(() => new Dog("Lassie"));