C# Singleton pattern using Lazy<T>
Asked Answered
S

1

5

I was reading this article by Jon Skeet.

In one the samples, he talks about using Lazy<T> to implement singleton pattern.

This is how the code looks:

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

He does mention at the end

  It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that. 

IsValueCreated indicates whether the lazy object is initialized or not.

I am wondering to ensure this class remains Singleton (only one insteace is created), where and how I would use IsValueCreated property ?

Spheroid answered 18/1, 2023 at 4:51 Comment(3)
To ensure a singleton, you don't need to worry about the IsValueCreated. Lazy<T> will do that for you, internally checking the Value delegate has been executed and if so, just return the martialized value, not execute the delegate again.Doublefaced
@PaulG: can you please add sample code for Value delegate has been executed and if so, just return the martialized value, not execute the delegate againSpheroid
Per your example the delegate is the Func that creates the instance of the Singleton () => new Singleton(). On the first access of the Value property the delegate or Func will be executed, materializing the value which will then be remembered. Subsequent accessors of Value will get this value, and the delegate or Func will not be re-materialized.Doublefaced
M
6

Lazy<T> ensures that only a single instance is ever created, and that instance will be returned when accessing the Value property - however, the creation of such instance is delayed until the first call to Value.

That means, for the given code sample you do not need to check if the instance has already been initialized - this is what Lazy does for you.

However, you have the ability to check so, which could be useful when dealing with a T of IDisposable (or anything that implements this interface). In that case, you can check for IsValueCreated in the dispose method, before trying to call Dispose() on that object (which would in turn uselessly force the creation of the lazy).

Myrtia answered 18/1, 2023 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.