#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.

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

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 comment