Jack
Jack
CC#
Created by Jack on 4/5/2024 in #help
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.
11 replies