Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton class design in C#, are these two classes equivalent?

I was reading up on singleton class design in C# on this great resource and decided to go with alternative 4:

public sealed class Singleton1
{
    static readonly Singleton1 _instance = new Singleton1();

    static Singleton1()
    {
    }

    Singleton1()
    {
    }

    public static Singleton1 Instance
    {
        get
        {
            return _instance;
        }
    }
}

Now I wonder if this can be rewritten using auto properties like this?

public sealed class Singleton2
{
    static Singleton2()
    {
        Instance = new Singleton2();
    }

    Singleton2()
    {
    }

    public static Singleton2 Instance { get; private set; }
}

If its only a matter of readability I definitely prefer the second version, but I want to get it right.

like image 410
Oskar Avatar asked Dec 23 '22 04:12

Oskar


1 Answers

It would work correctly, but it is not really the same.

Even if the property is marked as private, it is not read-only (e.g. assignable in the constructor only). Therefore you should use the first variant, which expresses the intent of having a variable (reference) which does not change after its initial assignment.

like image 132
Lucero Avatar answered Dec 28 '22 06:12

Lucero