Why is "readonly" important in the next Singleton implementation?

public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

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

I think that even when deleting a keyword readonlyfrom an instance of an element, a instancesingleton will work equally well.

  • Its static, only one instance will exist.
  • The value of can not changes because it does not have a setter.
  • Its sealed class cannot be a subclass.

Please help me correct my understanding of the concepts here.

+3
source share
4 answers

, readonly, Singleton. , - , , , readonly , .

EDIT :

  • , .
  • can not , .

, , . , - . , , . , , singleton , readonly . , , , : ) ) .

+9

readonly , , , . readonly , . .

+7

, - . readonly - . readonly - .

, , :

public sealed class Singleton
{
    private Singleton()
    {
       // Initialize here
    }

    private static volatile Singleton _singletonInstance;

    private static readonly Object syncRoot = new Object();

    public static Singleton Instance
    {
       get
       {
          if(_singletonInstance == null)
          {
             lock(syncRoot))
             {
                if(_singletonInstance == null)
                {   
                   _singletonInstance = new Singleton();
                }
             }
          }

          return _singletonInstance;
       }           
    }
}
0

readonly , OneAtaTimeleton ( Singleton).

Why? Well, the class contained some configuration, which I wanted so that the user (administrator) could change while the application was running. So, I added a static Reload () method to the class, which has:

instance = new Configuration();

therefore, you must remove readonly.

The private version of the constructor loads the configuration (via a non-static method).

0
source

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


All Articles