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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With