Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'readonly' essential in the following implementation of Singleton?

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 even on removing readonly keyword from the instance member instantiation, the singleton would still work equally well.

  • Its static, only one instance would exist.
  • The value cant change, as it has no setter.
  • Its a sealed class, cant be subclassed.

Please help me correct my understanding of the concepts here.

like image 739
Danish Khan Avatar asked Jan 28 '11 08:01

Danish Khan


2 Answers

Because if the field were not marked readonly it could be modified within the Singleton class. Of course, it still could not be modified by the outside world, but a singleton really isn't a singleton if there is more than one instance of it during the lifetime of your program, and the readonly specifier enforces the semantics that you want in a singleton class.

EDIT in response to:

  1. Its static, only one instance would exist.
  2. The value cant change, as it has no setter.

Static variables can certainly be set to reference different objects at runtime. The value can change, if only within the class due to it being private. If the class were implemented such that the field was only ever assigned to once, it wouldn't be a problem in practice. However, since the assumed intention is that the singleton instance will never change, the readonly modifier guarantees those semantics outside of the constructor. It's not essential because clients of the class cannot change the reference, but it is preferred because it a) makes the intent of the code clear, and b) prevents the reference from being changed even within the class.

like image 86
Ed S. Avatar answered Nov 07 '22 21:11

Ed S.


Using readonly is not essential in this case but it is something that enforces the semantics of the code by indicating the nature of the field. Personally I always use the readonly keyword for all field declarations whose value is going to be initialized only once. It also might help the compiler perform some optimizations under certain circumstances.

like image 8
Darin Dimitrov Avatar answered Nov 07 '22 21:11

Darin Dimitrov