#942 – The Case for Lazy Instantiation

Assume that we create some large data item in an object, e.g. the listofAllFamousDogs object in the sample below:

    public class Dog
        public string Name { get; set; }

        public Dog(string name)
            Name = name;

        public void Bark()

        private static List<Dog> listOfAllFamousDogs = GenerateBigListOfFamousDogs();

        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 { return listOfAllFamousDogs.Contains(this); }

The problem with this is that we end up creating the big list when we first use the class–whether or not we’ll later use the IsFamous property.

            Dog bob = new Dog("Bob");

What we need is to lazily instantiate this list.  That is–wait to create the list until we actually need it.


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

4 Responses to #942 – The Case for Lazy Instantiation

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

  2. Pingback: Ajax Control Toolkit Supports jQuery - Daily Six Pack: October 2, 2013

  3. Pingback: #943 – Lazy Instantiation, Solution #1 | 2,000 Things You Should Know About C#

  4. 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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: