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.
Please help me correct my understanding of the concepts here.
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:
- Its static, only one instance would exist.
- 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.
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.
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