stephen
stephen

Reputation: 385

C# singleton instance is never null

I am attempting to implement a singleton pattern in an Azure webjob. Debugging locally the instance is never null. It is always set to the singleton object itself. I feel I'm missing something brutally obvious here.

public sealed class HubErrorList
{
    private static volatile HubErrorList instance;
    private static object syncRoot = new Object();

    private HubErrorList() {}

    public static HubErrorList Instance
    {
        get {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new HubErrorList();
                    }
                }
            }
            return instance;
        }
    }
}

Upvotes: 1

Views: 1478

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564851

The instance will remain null until the property is accessed. Depending on how you're inspecting this, your tooling may be causing that discrepancy.

That being said, a simpler and nicer "lazy initialized" singleton pattern would be to use Lazy<T> instead:

public sealed class HubErrorList
{
    private static Lazy<HubErrorList> instance = new Lazy<HubErrorList>(() => new HubErrorList());
    private HubErrorList() {}

    public static HubErrorList Instance { get { return instance.Value; } }
}

Upvotes: 3

Related Questions