#946 – Specifying Whether Lazy Instantiated Object Should Be Thread-Safe

You can use the Lazy<T> class to declare an object that will be lazily instantiated–that is, created just before it is used.

In the example below, we indicate that the listOfAllFamousDogs object should only be created (by calling GenerateBigListOfFamousDogs) just before it is referenced.  The GenerateBigListOfFamousDogs method returns an instance of List<Dog>.

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

In the Lazy<T> constructor, we specify a delegate that will be called to initialize our object.  By default, this results in a thread-safe implementation that lazily instantiates the specified object.

If we do not need thread-safety, we can pass a second parameter to the Lazy<T> constructor, with a value of false.

        // No need for thread safety
        private static Lazy<List<Dog>> listOfAllFamousDogs = new Lazy<List<Dog>> (GenerateBigListOfFamousDogs, false);

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

4 Responses to #946 – Specifying Whether Lazy Instantiated Object Should Be Thread-Safe

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

  2. Dirk Strauss says:

    This is awesome Sean! Thank you!

  3. Pingback: Windows 8.1 Mail Experience In The Daily Six Pack: October 8, 2013

Leave a reply to Dirk Strauss Cancel reply