#943 – Lazy Instantiation, Solution #1

There are cases when we have a large amount of data to allocate in a class, either in an instance of the class or as static data.  We want to allocate and initialize the data as late as possible, i.e. just before we need to use the data.  This is know as lazy instantiation.

One method for lazy instantiation is to check to see if the data is instantiated, wherever we try to use it.

        private static List<Dog> listOfAllFamousDogs = null;

        private static List<Dog> GenerateBigListOfFamousDogs()
        {
            Console.WriteLine("Loading big list of famous dogs!");
            List<Dog> bigList = new List<Dog>();
            bigList.Add(new Dog("Lassie"));
            bigList.Add(new Dog("Rin Tin Tin"));
            // load 1,000 more dogs here

            return bigList;
        }

        public bool IsFamous
        {
            get
            {
                if (listOfAllFamousDogs == null)
                    listOfAllFamousDogs = GenerateBigListOfFamousDogs();

                return listOfAllFamousDogs.Contains(this);
            }
        }

We get lazy instantiation here–the list isn’t initialized until we use the IsFamous property.  This solution, however, is not thread-safe.

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.

3 Responses to #943 – Lazy Instantiation, Solution #1

  1. Pingback: Dew Drop – October 2, 2013 (#1,636) | Morning Dew

  2. Pingback: Dread Pirate Roberts Nabbed In The Daily Six Pack: September 3, 2013

  3. Pingback: #944 – Lazy Instantiation, Solution #2 | 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: