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 T 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:
1
2
3
4
5
| private static List<Dog> listOfAllFamousDogs = GenerateBigListOfFamousDogs();public bool IsFamous{ get { return listOfAllFamousDogs.Contains(this); }} |
You do this:
1
2
3
4
5
| private static Lazy<List<Dog>> listOfAllFamousDogs = new Lazy<List<Dog>> (GenerateBigListOfFamousDogs);public bool IsFamous{ get { return <span class="skimlinks-unlinked">listOfAllFamousDogs.Value.Contains(this</span>); }} |
Note that you also use the Value property of the new Lazy<T> object to get at the underlying object.

