Vijjendra
Vijjendra

Reputation: 25223

What is System.Lazy<T> and the Singleton Design Pattern

Can anyone help me to understand the benefit of using System.Lazy with Singleton Design Pattern.

Upvotes: 13

Views: 10379

Answers (2)

Ali Ferhat
Ali Ferhat

Reputation: 2579

The best source on C# Singletons (also covers Lazy<>) belongs to Jon Skeet: http://csharpindepth.com/Articles/General/Singleton.aspx

Suppose you want to have a class that :

  • represents a unique resource, so it should have a unique instance,
  • the instance needs an expensive initialization,
  • the initialization parameters will be available only at the run-time,
  • there are cases which you will not use the object after all,
  • there are more than one threads that could try to initialize the singleton object simultaneously,
  • etc.

If most of the above conditions are true, you will need to ensure that the class is Singleton, and the unique instance is lazily initialized (not initialized until needed) If you target C# 4.0 or later, using Lazy<> makes your design simpler, more readable and easier to remember.

Upvotes: 22

djna
djna

Reputation: 55907

The docs say

Use an instance of Lazy(Of T) to defer the creation of a large or resource-intensive object or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

So you make the singleton instance only if you need it.

Lazy instantiation is useful generally so that all the creation costs are not paid when the application insitialises - may give a nicer user experience.

Upvotes: 2

Related Questions