rastbin
rastbin

Reputation: 105

c# Singleton Pattern vs Static Property

When I tried to use 2 different versions of the same class , they act actually the same.

I searched but can't find a satisfied answer for this question

What are the differences between Singleton and static property below 2 example, it is about initialization time ? and how can i observe differences ?

Edit : I don't ask about differences static class and singleton. Both of them non static, only difference is, first one initialized in Instance property, second one initialized directly

public sealed class Singleton
{
    private static Singleton instance;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

public sealed class Singleton2
{
    private static Singleton2 instance = new Singleton2();

    private Singleton2()
    {
    }

    public static Singleton2 Instance
    {
        get
        {
            return instance;
        }
    }
}

Upvotes: 4

Views: 2966

Answers (2)

Servy
Servy

Reputation: 203802

Your first singleton implementation isn't thread safe; if multiple threads try to create a singleton at the same time it's possible for two instances to end up being created. Your second implementation doesn't have that flaw.

Other than that, they're functionally the same.

Upvotes: 1

mnwsmit
mnwsmit

Reputation: 1173

The instance of the Singleton class will be created the first time it is requested by the Singleton.Instance method.

The instance of Singleton2 will be created on initialization of its type which can be caused by several mechanisms. It will certainly be created before accessing any property or method on the Singleton2 class

Upvotes: 0

Related Questions