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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: