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

Advertisement