5 out of 12 rated this helpful - Rate this topic

Lazy<T> Class

Updated: April 2011

Provides support for lazy initialization.

System.Object
  System.Lazy<T>
    System.Lazy<T, TMetadata>

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
[SerializableAttribute]
[ComVisibleAttribute(false)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public class Lazy<T>

Type Parameters

T

Specifies the type of object that is being lazily initialized.

The Lazy<T> type exposes the following members.

  Name Description
Public method Supported by Portable Class Library Lazy<T>() Initializes a new instance of the Lazy<T> class. When lazy initialization occurs, the default constructor of the target type is used.
Public method Supported by Portable Class Library Lazy<T>(Boolean) Initializes a new instance of the Lazy<T> class. When lazy initialization occurs, the default constructor of the target type and the specified initialization mode are used.
Public method Supported by Portable Class Library Lazy<T>(Func<T>) Initializes a new instance of the Lazy<T> class. When lazy initialization occurs, the specified initialization function is used.
Public method Supported by Portable Class Library Lazy<T>(LazyThreadSafetyMode) Initializes a new instance of the Lazy<T> class that uses the default constructor of T and the specified thread-safety mode.
Public method Supported by Portable Class Library Lazy<T>(Func<T>, Boolean) Initializes a new instance of the Lazy<T> class. When lazy initialization occurs, the specified initialization function and initialization mode are used.
Public method Supported by Portable Class Library Lazy<T>(Func<T>, LazyThreadSafetyMode) Initializes a new instance of the Lazy<T> class that uses the specified initialization function and thread-safety mode.
Top
  Name Description
Public property Supported by Portable Class Library IsValueCreated Gets a value that indicates whether a value has been created for this Lazy<T> instance.
Public property Supported by Portable Class Library Value Gets the lazily initialized value of the current Lazy<T> instance.
Top
  Name Description
Public method Supported by Portable Class Library Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by Portable Class Library Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by Portable Class Library GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method Supported by Portable Class Library MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by Portable Class Library ToString Creates and returns a string representation of the Lazy<T>.Value property for this instance. (Overrides Object.ToString().)
Top

Lazy initialization occurs the first time the Lazy<T>.Value property is accessed.

Use an instance of Lazy<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.

Note Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

.NET Framework

Supported in: 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

By default, all public and protected members of the Lazy<T> class are thread safe and may be used concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance, using parameters to the type's constructors.

Date

History

Reason

April 2011

Correction: The ToString method does not cause initialization.

Customer feedback.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Invalidation

It is really a strange thing.

It is not support Invalidation, so it is used really for lazy objects that is not invalidated.

No support for Invalidating a Lazy<T> :(
Long ago, I rolled my own functional equivalent to Lazy<T>, $0with one major difference: The object exposed an Invalidate() $0 $0method that causes it to clear the contained value, and reset$0 $0its internal state to what it was when it was created. That in-$0 $0turn causes it to re-initialize the value the next time it is $0 $0accessed.$0 $0 $0$0 $0 $0That allows my home-grown implementation to serve as a $0 $0cache for holding a value with a high initialization cost, and$0 $0simplifying the code logic to manage and refresh the stored$0 $0value if it becomes stale or invalid. I routinely use that object$0 $0as a backing for properties whose values are expensive to$0 $0initialize or compute, so the computed value is cached and$0 $0can also be reinitialized whenever needed.$0 $0$0 $0 $0If Lazy<T> had such a method, it could be used to cache $0 $0values that can become invalid or stale at some point, and$0 $0need to be reinitialized.$0 $0 $0$0 $0 $0Another useful feature would be a way to declare a $0 $0property that is backed by a Lazy<T> (if it supported$0 $0invalidation), without having to write any code other$0 $0than the ValueFactory method.$0 $0$0 $0 $0$0 $0
LazySingleton
Regarding the singleton guarantee I found this implementation in the Task Parallel Library samples:

 public sealed class LazySingleton
    {
        private readonly static Lazy<LazySingleton> instance =
            new Lazy<LazySingleton>(() => new LazySingleton() );

        private LazySingleton() { }

        public static LazySingleton Instance
        {
            get { return instance.Value; }
        }
    }
Singleton gaurantee

The most important point of Lazy<T> is that it provides a neat implementation of the singleton pattern (only one instance will be created even under race conditions). For more information, see this comprehensive blog post: http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx

[Igby] No, this is not an implementation of the singleton pattern. This is an implementation of the lazy initiailization pattern. You can still create multiple instances:
Lazy<MyClass> lazy1 = new Lazy<MyClass>();
Lazy<MyClass> lazy2 = new Lazy<MyClass>();

[Glenn] It's true that you can create multiple instances of Lazy<MyClass>, but Luke's statement is still correct: Within a multithreaded program, an instance of Lazy<MyClass> can be used to implement a singleton MyClass that is shared by all threads. The Lazy<MyClass> must be thread safe, and all threads must access the same instance of Lazy<MyClass>.