C
C#12mo ago
Jack

A (hopefully) basic question about singleton instances

Hello, I don't know why but I am mixing things up in my head today with the singleton pattern. So the basic pattern goes something like this (simplified for brevity):
public Singleton
{
private static Singleton _instance;

public static Instance
{
if(_instance == null) _instance = new Singleton();
return _instance;
}
}
public Singleton
{
private static Singleton _instance;

public static Instance
{
if(_instance == null) _instance = new Singleton();
return _instance;
}
}
Now, in my head I had it that the private _instance variable should be an instance variable, i.e. not static. But all examples of the singleton pattern that I have found have the private instance being static. So why is this? Is there a problem with it being an instance variable? Is this just to absolutely ensure that there can only be one instance? I don't have any problem with using a private static field but it was in my head that it shouldn't be so I'd like to understand why I thought that and why it is wrong to do so.
6 Replies
XE SparkyCracked
XE SparkyCracked12mo ago
It's to make sure that there is only one intance of the class throughout the application.
Angius
Angius12mo ago
It's static so that only one can exist, on the type itself If it was an instance member, you would need... an instance Since you can have multiple instances, it's no longer a singleton Unless in the context of dependency injection, and the class being injected as a singleton
XE SparkyCracked
XE SparkyCracked12mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ You too fast for me...imma wait for you to go to bed lmao
Angius
Angius12mo ago
That won't happen for another 16-ish hours lol
XE SparkyCracked
XE SparkyCracked12mo ago
Ayt, so we gonna duo this lmao
Jack
JackOP12mo ago
:picard_facepalm: I think I need a holiday. This is so obvious thank you

Did you find this page helpful?