Designed by a Singleton class in C #, are these two classes equivalent?

I read about one design of the Singleton class in C # to this excellent 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 with auto properties like this?

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

If this is just a matter of readability, I definitely prefer the second version, but I want everything to be correct.

+4
source share
4 answers

It will work correctly, but in fact it is not.

Even if the property is marked as private, it is not readable (for example, it is assigned only in the constructor). Therefore, you should use the first option, which expresses the intention to have a variable (link) that does not change after its initial assignment.

+7
source

This is not equivalent, since the auto-prepare field will not be readonly .

+4
source

The property support field is not readonly , but since it is a private property, it is not so important. But the big advantage for the first implementation is that you can remove the static constructor, but for the second you use the static constructor. A static constructor can add a performance hit (see http://msdn.microsoft.com/en-us/library/ms182275(v=VS.100).aspx )

0
source

Another thing to consider here is that initializing a property is more work than just initializing a field.

The static constructor in Singleton2 calls the set method on the property, which then sets the value of the support field. I have no idea how and how this affects thread safety, but that's another difference.

0
source

Source: https://habr.com/ru/post/1306658/


All Articles