#947 – Specifying Lazy Instantiation Using a Lambda Expression

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"));

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #947 – Specifying Lazy Instantiation Using a Lambda Expression

  1. Pingback: Dew Drop – October 8, 2013 (#1,640) | Morning Dew

  2. Pingback: Test Driven Development Series - The Daily Six Pack, October 10, 2013

Leave a comment