#945 – Lazy Instantiation, an Easier Solution

The previous post showed how to implement lazy instantiation in a thread-safe manner, waiting to initialize an object until it is first used.

.NET 4.0 introduced the Lazy<T> class, which makes lazy instantiation much easier.  If you have an object that you want to instantiate as late as possible, you declare it to be of type Lazy<T>, where is the core type of your object.  You also specify a method to be called to do the actual initialization of the object.

So instead of doing this:

        private static List<Dog> listOfAllFamousDogs = GenerateBigListOfFamousDogs();
        public bool IsFamous
        {
            get { return listOfAllFamousDogs.Contains(this); }
        }

You do this:

        private static Lazy<List<Dog>> listOfAllFamousDogs = new Lazy<List<Dog>> (GenerateBigListOfFamousDogs);
        public bool IsFamous
        {
            get { return listOfAllFamousDogs.Value.Contains(this); }
        }

Note that you also use the Value property of the new Lazy<T> object to get at the underlying object.

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.

4 Responses to #945 – Lazy Instantiation, an Easier Solution

  1. Pingback: TweetBrander wants you - avid Twitter user? Write for their website

  2. Pingback: #946 – Specifying Whether Lazy Instantiated Object Should Be Thread-Safe | 2,000 Things You Should Know About C#

  3. Pingback: #947 – Specifying Lazy Instantiation Using a Lambda Expression | 2,000 Things You Should Know About C#

  4. Pingback: #948 – Using Lazy to Implement the Singleton Pattern | 2,000 Things You Should Know About C#

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: