#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()
        {
            Console.WriteLine("Woof!");
        }

        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");
            bob.Bark();

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

Advertisement